---
title: "Spring定时器的两种实现方式一（timer）"
author: "HelloJava1234"
date: "2012-04-01T18:40:00Z"
tags: []
slug: "spring-timer"
draft: false
lastmod: "2012-04-04T22:56:03Z"
id: 1474093
url: "https://hellojava1234.iteye.com/blog/1474093"
---

有两种流行Spring定时器配置：[Java](http://java.chinaitlab.com/)的Timer类和OpenSymphony的Quartz。

1.[Java](http://java.chinaitlab.com/) Timer定时

相信做软件的朋友都有这样的经历，我的软件是不是少了点什么东西呢？比如定时任务啊，

就拿新闻发布系统来说，如果新闻的数据更新太快，势必涉及一个问题，这些新闻不能由人工的去发布，应该让系统自己发布，这就需要用到定时定制任务了，以前定制任务无非就是设计一个Thread，并且设置运行时间片，让它到了那个时间执行一次，就ok了，让系统启动的时候启动它，想来也够简单的。不过有了spring，我想这事情就更简单了。

看看spring的配置文件，想来就只有这个配置文件了

xml 代码

01. &lt;beanid="infoCenterAutoBuildTask"
02. class="com.teesoo.teanet.scheduling.InfoCenterAutoBuildTask"&gt;
03. &lt;propertyname="baseService"ref="baseService"/&gt;
04. &lt;propertyname="htmlCreator"ref="htmlCreator"/&gt;
05. &lt;/bean&gt;
06. &lt;beanid="scheduledTask"
07. class="org.springframework.scheduling.timer.ScheduledTimerTask"&gt;
08. &lt;!--wait10secondsbeforestartingrepeatedexecution--&gt;
09. &lt;propertyname="delay"value="10000"/&gt;
10. &lt;!--runevery50seconds--&gt;
11. &lt;propertyname="period"value="1000000"/&gt;
12. &lt;propertyname="timerTask"ref="infoCenterAutoBuildTask"/&gt;
13. &lt;/bean&gt;
14. &lt;beanid="timerFactory"class="org.springframework.scheduling.timer.TimerFactoryBean"&gt;
15. &lt;propertyname="scheduledTimerTasks"&gt;
16. &lt;list&gt;
17. &lt;!--seetheexampleabove--&gt;
18. &lt;refbean="scheduledTask"/&gt;
19. &lt;/list&gt;
20. &lt;/property&gt;
21. &lt;/bean&gt;

上面三个配置文件中只有一个配置文件是涉及到您自己的class的，其他的都是spring的类。很简单吧

我们只需要涉及一个class让他继承java.util.TimerTask;

java 代码

1. BaseTask**extends**java.util.TimerTask{
2. //用户只需要实现这个方面，把自己的任务放到这里
3. **public****void**run(){
4. }
5. }

下面让我们来看看 spring的源代码

java 代码

001. /*
002. \*Copyright2002-2005theoriginalauthororauthors.
003. \*
004. \*LicensedundertheApacheLicense,Version2.0(the"License");
005. \*youmaynotusethisfileexceptincompliancewiththeLicense.
006. \*YoumayobtainacopyoftheLicenseat
007. \*
008. \*http://www.apache.org/licenses/LICENSE-2.0
009. \*
010. \*Unlessrequiredbyapplicablelaworagreedtoinwriting,software
011. \*distributedundertheLicenseisdistributedonan"ASIS"BASIS,
012. \*WITHOUTWARRANTIESORCONDITIONSOFANYKIND,eitherexpressorimplied.
013. \*SeetheLicenseforthespecificlanguagegoverningpermissionsand
014. \*limitationsundertheLicense.
015. \*/
016. **package**org.springframework.scheduling.timer;
017. **import**java.util.TimerTask;
018. /\**
019. \*JavaBeanthatdescribesascheduledTimerTask,consistingof
020. \*theTimerTaskitself(oraRunnabletocreateaTimerTaskfor)
021. \*andadelayplusperiod.Periodneedstobespecified;
022. \*thereisnopointinadefaultforit.
023. \*
024. \*&lt;p&gt;TheJDKTimerdoesnotoffermoresophisticatedscheduling
025. \*optionssuchascronexpressions.ConsiderusingQuartzfor
026. \*suchadvancedneeds.
027. \*
028. \*&lt;p&gt;NotethatTimerusesaTimerTaskinstancethatisshared
029. \*betweenrepeatedexecutions,incontrasttoQuartzwhich
030. \*instantiatesanewJobforeachexecution.
031. \*
032. \*@authorJuergenHoeller
033. \*@since19.02.2004
034. \*@seejava.util.TimerTask
035. \*@seejava.util.Timer#schedule(TimerTask,long,long)
036. \*@seejava.util.Timer#scheduleAtFixedRate(TimerTask,long,long)
037. \*/
038. **public****class**ScheduledTimerTask{
039. **private**TimerTasktimerTask;
040. **private****long**delay=0;
041. **private****long**period=0;
042. **private****boolean**fixedRate=**false**;
043. /\**
044. \*CreateanewScheduledTimerTask,
045. \*tobepopulatedviabeanproperties.
046. \*@see#setTimerTask
047. \*@see#setDelay
048. \*@see#setPeriod
049. \*@see#setFixedRate
050. \*/
051. **public**ScheduledTimerTask(){
052. }
053. /\**
054. \*CreateanewScheduledTimerTask,withdefault
055. \*one-timeexecutionwithoutdelay.
056. \*@paramtimerTasktheTimerTasktoschedule
057. \*/
058. **public**ScheduledTimerTask(TimerTasktimerTask){
059. **this**.timerTask=timerTask;
060. }
061. /\**
062. \*CreateanewScheduledTimerTask,withdefault
063. \*one-timeexecutionwiththegivendelay.
064. \*@paramtimerTasktheTimerTasktoschedule
065. \*@paramdelaythedelaybeforestartingthetaskforthefirsttime(ms)
066. \*/
067. **public**ScheduledTimerTask(TimerTasktimerTask,**long**delay){
068. **this**.timerTask=timerTask;
069. **this**.delay=delay;
070. }
071. /\**
072. \*CreateanewScheduledTimerTask.
073. \*@paramtimerTasktheTimerTasktoschedule
074. \*@paramdelaythedelaybeforestartingthetaskforthefirsttime(ms)
075. \*@paramperiodtheperiodbetweenrepeatedtaskexecutions(ms)
076. \*@paramfixedRatewhethertoscheduleasfixed-rateexecution
077. \*/
078. **public**ScheduledTimerTask(TimerTasktimerTask,**long**delay,**long**period,**boolean**fixedRate){
079. **this**.timerTask=timerTask;
080. **this**.delay=delay;
081. **this**.period=period;
082. **this**.fixedRate=fixedRate;
083. }
084. /\**
085. \*CreateanewScheduledTimerTask,withdefault
086. \*one-timeexecutionwithoutdelay.
087. \*@paramtimerTasktheRunnabletoscheduleasTimerTask
088. \*/
089. **public**ScheduledTimerTask(RunnabletimerTask){
090. setRunnable(timerTask);
091. }
092. /\**
093. \*CreateanewScheduledTimerTask,withdefault
094. \*one-timeexecutionwiththegivendelay.
095. \*@paramtimerTasktheRunnabletoscheduleasTimerTask
096. \*@paramdelaythedelaybeforestartingthetaskforthefirsttime(ms)
097. \*/
098. **public**ScheduledTimerTask(RunnabletimerTask,**long**delay){
099. setRunnable(timerTask);
100. **this**.delay=delay;
101. }
102. /\**
103. \*CreateanewScheduledTimerTask.
104. \*@paramtimerTasktheRunnabletoscheduleasTimerTask
105. \*@paramdelaythedelaybeforestartingthetaskforthefirsttime(ms)
106. \*@paramperiodtheperiodbetweenrepeatedtaskexecutions(ms)
107. \*@paramfixedRatewhethertoscheduleasfixed-rateexecution
108. \*/
109. **public**ScheduledTimerTask(RunnabletimerTask,**long**delay,**long**period,**boolean**fixedRate){
110. setRunnable(timerTask);
111. **this**.delay=delay;
112. **this**.period=period;
113. **this**.fixedRate=fixedRate;
114. }
115. /\**
116. \*SettheRunnabletoscheduleasTimerTask.
117. \*@seeDelegatingTimerTask
118. \*/
119. **public****void**setRunnable(RunnabletimerTask){
120. **this**.timerTask=**new**DelegatingTimerTask(timerTask);
121. }
122. /\**
123. \*SettheTimerTasktoschedule.
124. \*/
125. **public****void**setTimerTask(TimerTasktimerTask){
126. **this**.timerTask=timerTask;
127. }
128. /\**
129. \*ReturntheTimerTasktoschedule.
130. \*/
131. **public**TimerTaskgetTimerTask(){
132. **return**timerTask;
133. }
134. /\**
135. \*Setthedelaybeforestartingthetaskforthefirsttime,
136. \*inmilliseconds.Defaultis0,immediatelystartingthe
137. \*taskaftersuccessfulscheduling.
138. \*/
139. **public****void**setDelay(**long**delay){
140. **this**.delay=delay;
141. }
142. /\**
143. \*Returnthedelaybeforestartingthejobforthefirsttime.
144. \*/
145. **public****long**getDelay(){
146. **return**delay;
147. }
148. /\**
149. \*Settheperiodbetweenrepeatedtaskexecutions,inmilliseconds.
150. \*Defaultis0,leadingtoone-timeexecution.Incaseofapositive
151. \*value,thetaskwillbeexecutedrepeatedly,withthegiveninterval
152. \*inbetweenexecutions.
153. \*&lt;p&gt;Notethatthesemanticsoftheperiodvarybetweenfixed-rate
154. \*andfixed-delayexecution.
155. \*@see#setFixedRate
156. \*/
157. **public****void**setPeriod(**long**period){
158. **this**.period=period;
159. }
160. /\**
161. \*Returntheperiodbetweenrepeatedtaskexecutions.
162. \*/
163. **public****long**getPeriod(){
164. **return**period;
165. }
166. /\**
167. \*Setwhethertoscheduleasfixed-rateexecution,ratherthan
168. \*fixed-delayexecution.Defaultis"false",i.e.fixeddelay.
169. \*&lt;p&gt;SeeTimerjavadocfordetailsonthoseexecutionmodes.
170. \*@seejava.util.Timer#schedule(TimerTask,long,long)
171. \*@seejava.util.Timer#scheduleAtFixedRate(TimerTask,long,long)
172. \*/
173. **public****void**setFixedRate(**boolean**fixedRate){
174. **this**.fixedRate=fixedRate;
175. }
176. /\**
177. \*Returnwhethertoscheduleasfixed-rateexecution.
178. \*/
179. **public****boolean**isFixedRate(){
180. **return**fixedRate;
181. }
182. }

说实话这个类也没什么，只是简单的包装了我们的timertask，里面也就只有几个属性，一个是时间片，一个是任务等。

真正运行我们的任务的类是：

java 代码

001. /*
002. \*Copyright2002-2006theoriginalauthororauthors.
003. \*
004. \*LicensedundertheApacheLicense,Version2.0(the"License");
005. \*youmaynotusethisfileexceptincompliancewiththeLicense.
006. \*YoumayobtainacopyoftheLicenseat
007. \*
008. \*http://www.apache.org/licenses/LICENSE-2.0
009. \*
010. \*Unlessrequiredbyapplicablelaworagreedtoinwriting,software
011. \*distributedundertheLicenseisdistributedonan"ASIS"BASIS,
012. \*WITHOUTWARRANTIESORCONDITIONSOFANYKIND,eitherexpressorimplied.
013. \*SeetheLicenseforthespecificlanguagegoverningpermissionsand
014. \*limitationsundertheLicense.
015. \*/
016. **package**org.springframework.scheduling.timer;
017. **import**java.util.Timer;
018. **import**org.apache.commons.logging.Log;
019. **import**org.apache.commons.logging.LogFactory;
020. **import**org.springframework.beans.factory.DisposableBean;
021. **import**org.springframework.beans.factory.FactoryBean;
022. **import**org.springframework.beans.factory.InitializingBean;
023. /\**
024. \*FactoryBeanthatsetsupaJDK1.3+Timerandexposesitforbeanreferences.
025. \*
026. \*&lt;p&gt;AllowsforregistrationofScheduledTimerTasks,automaticallystarting
027. \*theTimeroninitializationandcancellingitondestructionofthecontext.
028. \*Inscenariosthatjustrequirestaticregistrationoftasksatstartup,
029. \*thereisnoneedtoaccesstheTimerinstanceitselfinapplicationcode.
030. \*
031. \*&lt;p&gt;NotethatTimerusesaTimerTaskinstancethatissharedbetween
032. \*repeatedexecutions,incontrasttoQuartzwhichinstantiatesanew
033. \*Jobforeachexecution.
034. \*
035. \*@authorJuergenHoeller
036. \*@since19.02.2004
037. \*@seeScheduledTimerTask
038. \*@seejava.util.Timer
039. \*@seejava.util.TimerTask
040. \*/
041. **public****class**TimerFactoryBean**implements**FactoryBean,InitializingBean,DisposableBean{
042. **protected****final**Loglogger=LogFactory.getLog(getClass());
043. **private**ScheduledTimerTask\[]scheduledTimerTasks;
044. **private****boolean**daemon=**false**;
045. **private**Timertimer;
046. /\**
047. \*RegisteralistofScheduledTimerTaskobjectswiththeTimerthat
048. \*thisFactoryBeancreates.DependingoneachSchedulerTimerTask's
049. \*settings,itwillberegisteredviaoneofTimer'sschedulemethods.
050. \*@seejava.util.Timer#schedule(java.util.TimerTask,long)
051. \*@seejava.util.Timer#schedule(java.util.TimerTask,long,long)
052. \*@seejava.util.Timer#scheduleAtFixedRate(java.util.TimerTask,long,long)
053. \*/
054. **public****void**setScheduledTimerTasks(ScheduledTimerTask\[]scheduledTimerTasks){
055. **this**.scheduledTimerTasks=scheduledTimerTasks;
056. }
057. /\**
058. \*Setwhetherthetimershoulduseadaemonthread,
059. \*justexecutingaslongastheapplicationitselfisrunning.
060. \*&lt;p&gt;Defaultis"false":Thetimerwillautomaticallygetcancelledon
061. \*destructionofthisFactoryBean.Hence,iftheapplicationshutsdown,
062. \*taskswillbydefaultfinishtheirexecution.Specify"true"foreager
063. \*shutdownofthreadsthatexecutetasks.
064. \*@seejava.util.Timer#Timer(boolean)
065. \*/
066. **public****void**setDaemon(**boolean**daemon){
067. **this**.daemon=daemon;
068. }
069. **public****void**afterPropertiesSet(){
070. logger.info("InitializingTimer");
071. **this**.timer=createTimer(**this**.daemon);
072. //RegisterallScheduledTimerTasks.
073. **if**(**this**.scheduledTimerTasks!=**null**){
074. **for**(**int**i=0;i&lt;**this**.scheduledTimerTasks.length;i++){
075. ScheduledTimerTaskscheduledTask=**this**.scheduledTimerTasks\[i];
076. **if**(scheduledTask.getPeriod()&gt;0){
077. //repeatedtaskexecution
078. **if**(scheduledTask.isFixedRate()){
079. **this**.timer.scheduleAtFixedRate(
080. scheduledTask.getTimerTask(),scheduledTask.getDelay(),scheduledTask.getPeriod());
081. }
082. **else**{
083. **this**.timer.schedule(
084. scheduledTask.getTimerTask(),scheduledTask.getDelay(),scheduledTask.getPeriod());
085. }
086. }
087. **else**{
088. //One-timetaskexecution.
089. **this**.timer.schedule(scheduledTask.getTimerTask(),scheduledTask.getDelay());
090. }
091. }
092. }
093. }
094. /\**
095. \*CreateanewTimerinstance.Calledby&lt;code&gt;afterPropertiesSet&lt;/code&gt;.
096. \*CanbeoverriddeninsubclassestoprovidecustomTimersubclasses.
097. \*@paramdaemonwhethertocreateaTimerthatrunsasdaemonthread
098. \*@returnanewTimerinstance
099. \*@see#afterPropertiesSet()
100. \*@seejava.util.Timer#Timer(boolean)
101. \*/
102. **protected**TimercreateTimer(**boolean**daemon){
103. **return****new**Timer(daemon);
104. }
105. **public**ObjectgetObject(){
106. **return****this**.timer;
107. }
108. **public**ClassgetObjectType(){
109. **return**Timer.**class**;
110. }
111. **public****boolean**isSingleton(){
112. **return****true**;
113. }
114. /\**
115. \*CanceltheTimeronbeanfactoryshutdown,stoppingallscheduledtasks.
116. \*@seejava.util.Timer#cancel()
117. \*/
118. **public****void**destroy(){
119. logger.info("CancellingTimer");
120. **this**.timer.cancel();
121. }
122. }

这个类就是运行我们任务的类了，我们可以定制N个任务，只需要塞到这里就ok了

有两种流行Spring定时器配置：[Java](http://java.chinaitlab.com/)的Timer类和OpenSymphony的Quartz。

1.[Java](http://java.chinaitlab.com/) Timer定时

相信做软件的朋友都有这样的经历，我的软件是不是少了点什么东西呢？比如定时任务啊，

就拿新闻发布系统来说，如果新闻的数据更新太快，势必涉及一个问题，这些新闻不能由人工的去发布，应该让系统自己发布，这就需要用到定时定制任务了，以前定制任务无非就是设计一个Thread，并且设置运行时间片，让它到了那个时间执行一次，就ok了，让系统启动的时候启动它，想来也够简单的。不过有了spring，我想这事情就更简单了。

看看spring的配置文件，想来就只有这个配置文件了

xml 代码

01. &lt;beanid="infoCenterAutoBuildTask"
02. class="com.teesoo.teanet.scheduling.InfoCenterAutoBuildTask"&gt;
03. &lt;propertyname="baseService"ref="baseService"/&gt;
04. &lt;propertyname="htmlCreator"ref="htmlCreator"/&gt;
05. &lt;/bean&gt;
06. &lt;beanid="scheduledTask"
07. class="org.springframework.scheduling.timer.ScheduledTimerTask"&gt;
08. &lt;!--wait10secondsbeforestartingrepeatedexecution--&gt;
09. &lt;propertyname="delay"value="10000"/&gt;
10. &lt;!--runevery50seconds--&gt;
11. &lt;propertyname="period"value="1000000"/&gt;
12. &lt;propertyname="timerTask"ref="infoCenterAutoBuildTask"/&gt;
13. &lt;/bean&gt;
14. &lt;beanid="timerFactory"class="org.springframework.scheduling.timer.TimerFactoryBean"&gt;
15. &lt;propertyname="scheduledTimerTasks"&gt;
16. &lt;list&gt;
17. &lt;!--seetheexampleabove--&gt;
18. &lt;refbean="scheduledTask"/&gt;
19. &lt;/list&gt;
20. &lt;/property&gt;
21. &lt;/bean&gt;

上面三个配置文件中只有一个配置文件是涉及到您自己的class的，其他的都是spring的类。很简单吧

我们只需要涉及一个class让他继承java.util.TimerTask;

java 代码

1. BaseTask**extends**java.util.TimerTask{
2. //用户只需要实现这个方面，把自己的任务放到这里
3. **public****void**run(){
4. }
5. }

下面让我们来看看 spring的源代码

java 代码

001. /*
002. \*Copyright2002-2005theoriginalauthororauthors.
003. \*
004. \*LicensedundertheApacheLicense,Version2.0(the"License");
005. \*youmaynotusethisfileexceptincompliancewiththeLicense.
006. \*YoumayobtainacopyoftheLicenseat
007. \*
008. \*http://www.apache.org/licenses/LICENSE-2.0
009. \*
010. \*Unlessrequiredbyapplicablelaworagreedtoinwriting,software
011. \*distributedundertheLicenseisdistributedonan"ASIS"BASIS,
012. \*WITHOUTWARRANTIESORCONDITIONSOFANYKIND,eitherexpressorimplied.
013. \*SeetheLicenseforthespecificlanguagegoverningpermissionsand
014. \*limitationsundertheLicense.
015. \*/
016. **package**org.springframework.scheduling.timer;
017. **import**java.util.TimerTask;
018. /\**
019. \*JavaBeanthatdescribesascheduledTimerTask,consistingof
020. \*theTimerTaskitself(oraRunnabletocreateaTimerTaskfor)
021. \*andadelayplusperiod.Periodneedstobespecified;
022. \*thereisnopointinadefaultforit.
023. \*
024. \*&lt;p&gt;TheJDKTimerdoesnotoffermoresophisticatedscheduling
025. \*optionssuchascronexpressions.ConsiderusingQuartzfor
026. \*suchadvancedneeds.
027. \*
028. \*&lt;p&gt;NotethatTimerusesaTimerTaskinstancethatisshared
029. \*betweenrepeatedexecutions,incontrasttoQuartzwhich
030. \*instantiatesanewJobforeachexecution.
031. \*
032. \*@authorJuergenHoeller
033. \*@since19.02.2004
034. \*@seejava.util.TimerTask
035. \*@seejava.util.Timer#schedule(TimerTask,long,long)
036. \*@seejava.util.Timer#scheduleAtFixedRate(TimerTask,long,long)
037. \*/
038. **public****class**ScheduledTimerTask{
039. **private**TimerTasktimerTask;
040. **private****long**delay=0;
041. **private****long**period=0;
042. **private****boolean**fixedRate=**false**;
043. /\**
044. \*CreateanewScheduledTimerTask,
045. \*tobepopulatedviabeanproperties.
046. \*@see#setTimerTask
047. \*@see#setDelay
048. \*@see#setPeriod
049. \*@see#setFixedRate
050. \*/
051. **public**ScheduledTimerTask(){
052. }
053. /\**
054. \*CreateanewScheduledTimerTask,withdefault
055. \*one-timeexecutionwithoutdelay.
056. \*@paramtimerTasktheTimerTasktoschedule
057. \*/
058. **public**ScheduledTimerTask(TimerTasktimerTask){
059. **this**.timerTask=timerTask;
060. }
061. /\**
062. \*CreateanewScheduledTimerTask,withdefault
063. \*one-timeexecutionwiththegivendelay.
064. \*@paramtimerTasktheTimerTasktoschedule
065. \*@paramdelaythedelaybeforestartingthetaskforthefirsttime(ms)
066. \*/
067. **public**ScheduledTimerTask(TimerTasktimerTask,**long**delay){
068. **this**.timerTask=timerTask;
069. **this**.delay=delay;
070. }
071. /\**
072. \*CreateanewScheduledTimerTask.
073. \*@paramtimerTasktheTimerTasktoschedule
074. \*@paramdelaythedelaybeforestartingthetaskforthefirsttime(ms)
075. \*@paramperiodtheperiodbetweenrepeatedtaskexecutions(ms)
076. \*@paramfixedRatewhethertoscheduleasfixed-rateexecution
077. \*/
078. **public**ScheduledTimerTask(TimerTasktimerTask,**long**delay,**long**period,**boolean**fixedRate){
079. **this**.timerTask=timerTask;
080. **this**.delay=delay;
081. **this**.period=period;
082. **this**.fixedRate=fixedRate;
083. }
084. /\**
085. \*CreateanewScheduledTimerTask,withdefault
086. \*one-timeexecutionwithoutdelay.
087. \*@paramtimerTasktheRunnabletoscheduleasTimerTask
088. \*/
089. **public**ScheduledTimerTask(RunnabletimerTask){
090. setRunnable(timerTask);
091. }
092. /\**
093. \*CreateanewScheduledTimerTask,withdefault
094. \*one-timeexecutionwiththegivendelay.
095. \*@paramtimerTasktheRunnabletoscheduleasTimerTask
096. \*@paramdelaythedelaybeforestartingthetaskforthefirsttime(ms)
097. \*/
098. **public**ScheduledTimerTask(RunnabletimerTask,**long**delay){
099. setRunnable(timerTask);
100. **this**.delay=delay;
101. }
102. /\**
103. \*CreateanewScheduledTimerTask.
104. \*@paramtimerTasktheRunnabletoscheduleasTimerTask
105. \*@paramdelaythedelaybeforestartingthetaskforthefirsttime(ms)
106. \*@paramperiodtheperiodbetweenrepeatedtaskexecutions(ms)
107. \*@paramfixedRatewhethertoscheduleasfixed-rateexecution
108. \*/
109. **public**ScheduledTimerTask(RunnabletimerTask,**long**delay,**long**period,**boolean**fixedRate){
110. setRunnable(timerTask);
111. **this**.delay=delay;
112. **this**.period=period;
113. **this**.fixedRate=fixedRate;
114. }
115. /\**
116. \*SettheRunnabletoscheduleasTimerTask.
117. \*@seeDelegatingTimerTask
118. \*/
119. **public****void**setRunnable(RunnabletimerTask){
120. **this**.timerTask=**new**DelegatingTimerTask(timerTask);
121. }
122. /\**
123. \*SettheTimerTasktoschedule.
124. \*/
125. **public****void**setTimerTask(TimerTasktimerTask){
126. **this**.timerTask=timerTask;
127. }
128. /\**
129. \*ReturntheTimerTasktoschedule.
130. \*/
131. **public**TimerTaskgetTimerTask(){
132. **return**timerTask;
133. }
134. /\**
135. \*Setthedelaybeforestartingthetaskforthefirsttime,
136. \*inmilliseconds.Defaultis0,immediatelystartingthe
137. \*taskaftersuccessfulscheduling.
138. \*/
139. **public****void**setDelay(**long**delay){
140. **this**.delay=delay;
141. }
142. /\**
143. \*Returnthedelaybeforestartingthejobforthefirsttime.
144. \*/
145. **public****long**getDelay(){
146. **return**delay;
147. }
148. /\**
149. \*Settheperiodbetweenrepeatedtaskexecutions,inmilliseconds.
150. \*Defaultis0,leadingtoone-timeexecution.Incaseofapositive
151. \*value,thetaskwillbeexecutedrepeatedly,withthegiveninterval
152. \*inbetweenexecutions.
153. \*&lt;p&gt;Notethatthesemanticsoftheperiodvarybetweenfixed-rate
154. \*andfixed-delayexecution.
155. \*@see#setFixedRate
156. \*/
157. **public****void**setPeriod(**long**period){
158. **this**.period=period;
159. }
160. /\**
161. \*Returntheperiodbetweenrepeatedtaskexecutions.
162. \*/
163. **public****long**getPeriod(){
164. **return**period;
165. }
166. /\**
167. \*Setwhethertoscheduleasfixed-rateexecution,ratherthan
168. \*fixed-delayexecution.Defaultis"false",i.e.fixeddelay.
169. \*&lt;p&gt;SeeTimerjavadocfordetailsonthoseexecutionmodes.
170. \*@seejava.util.Timer#schedule(TimerTask,long,long)
171. \*@seejava.util.Timer#scheduleAtFixedRate(TimerTask,long,long)
172. \*/
173. **public****void**setFixedRate(**boolean**fixedRate){
174. **this**.fixedRate=fixedRate;
175. }
176. /\**
177. \*Returnwhethertoscheduleasfixed-rateexecution.
178. \*/
179. **public****boolean**isFixedRate(){
180. **return**fixedRate;
181. }
182. }

说实话这个类也没什么，只是简单的包装了我们的timertask，里面也就只有几个属性，一个是时间片，一个是任务等。

真正运行我们的任务的类是：

java 代码

001. /*
002. \*Copyright2002-2006theoriginalauthororauthors.
003. \*
004. \*LicensedundertheApacheLicense,Version2.0(the"License");
005. \*youmaynotusethisfileexceptincompliancewiththeLicense.
006. \*YoumayobtainacopyoftheLicenseat
007. \*
008. \*http://www.apache.org/licenses/LICENSE-2.0
009. \*
010. \*Unlessrequiredbyapplicablelaworagreedtoinwriting,software
011. \*distributedundertheLicenseisdistributedonan"ASIS"BASIS,
012. \*WITHOUTWARRANTIESORCONDITIONSOFANYKIND,eitherexpressorimplied.
013. \*SeetheLicenseforthespecificlanguagegoverningpermissionsand
014. \*limitationsundertheLicense.
015. \*/
016. **package**org.springframework.scheduling.timer;
017. **import**java.util.Timer;
018. **import**org.apache.commons.logging.Log;
019. **import**org.apache.commons.logging.LogFactory;
020. **import**org.springframework.beans.factory.DisposableBean;
021. **import**org.springframework.beans.factory.FactoryBean;
022. **import**org.springframework.beans.factory.InitializingBean;
023. /\**
024. \*FactoryBeanthatsetsupaJDK1.3+Timerandexposesitforbeanreferences.
025. \*
026. \*&lt;p&gt;AllowsforregistrationofScheduledTimerTasks,automaticallystarting
027. \*theTimeroninitializationandcancellingitondestructionofthecontext.
028. \*Inscenariosthatjustrequirestaticregistrationoftasksatstartup,
029. \*thereisnoneedtoaccesstheTimerinstanceitselfinapplicationcode.
030. \*
031. \*&lt;p&gt;NotethatTimerusesaTimerTaskinstancethatissharedbetween
032. \*repeatedexecutions,incontrasttoQuartzwhichinstantiatesanew
033. \*Jobforeachexecution.
034. \*
035. \*@authorJuergenHoeller
036. \*@since19.02.2004
037. \*@seeScheduledTimerTask
038. \*@seejava.util.Timer
039. \*@seejava.util.TimerTask
040. \*/
041. **public****class**TimerFactoryBean**implements**FactoryBean,InitializingBean,DisposableBean{
042. **protected****final**Loglogger=LogFactory.getLog(getClass());
043. **private**ScheduledTimerTask\[]scheduledTimerTasks;
044. **private****boolean**daemon=**false**;
045. **private**Timertimer;
046. /\**
047. \*RegisteralistofScheduledTimerTaskobjectswiththeTimerthat
048. \*thisFactoryBeancreates.DependingoneachSchedulerTimerTask's
049. \*settings,itwillberegisteredviaoneofTimer'sschedulemethods.
050. \*@seejava.util.Timer#schedule(java.util.TimerTask,long)
051. \*@seejava.util.Timer#schedule(java.util.TimerTask,long,long)
052. \*@seejava.util.Timer#scheduleAtFixedRate(java.util.TimerTask,long,long)
053. \*/
054. **public****void**setScheduledTimerTasks(ScheduledTimerTask\[]scheduledTimerTasks){
055. **this**.scheduledTimerTasks=scheduledTimerTasks;
056. }
057. /\**
058. \*Setwhetherthetimershoulduseadaemonthread,
059. \*justexecutingaslongastheapplicationitselfisrunning.
060. \*&lt;p&gt;Defaultis"false":Thetimerwillautomaticallygetcancelledon
061. \*destructionofthisFactoryBean.Hence,iftheapplicationshutsdown,
062. \*taskswillbydefaultfinishtheirexecution.Specify"true"foreager
063. \*shutdownofthreadsthatexecutetasks.
064. \*@seejava.util.Timer#Timer(boolean)
065. \*/
066. **public****void**setDaemon(**boolean**daemon){
067. **this**.daemon=daemon;
068. }
069. **public****void**afterPropertiesSet(){
070. logger.info("InitializingTimer");
071. **this**.timer=createTimer(**this**.daemon);
072. //RegisterallScheduledTimerTasks.
073. **if**(**this**.scheduledTimerTasks!=**null**){
074. **for**(**int**i=0;i&lt;**this**.scheduledTimerTasks.length;i++){
075. ScheduledTimerTaskscheduledTask=**this**.scheduledTimerTasks\[i];
076. **if**(scheduledTask.getPeriod()&gt;0){
077. //repeatedtaskexecution
078. **if**(scheduledTask.isFixedRate()){
079. **this**.timer.scheduleAtFixedRate(
080. scheduledTask.getTimerTask(),scheduledTask.getDelay(),scheduledTask.getPeriod());
081. }
082. **else**{
083. **this**.timer.schedule(
084. scheduledTask.getTimerTask(),scheduledTask.getDelay(),scheduledTask.getPeriod());
085. }
086. }
087. **else**{
088. //One-timetaskexecution.
089. **this**.timer.schedule(scheduledTask.getTimerTask(),scheduledTask.getDelay());
090. }
091. }
092. }
093. }
094. /\**
095. \*CreateanewTimerinstance.Calledby&lt;code&gt;afterPropertiesSet&lt;/code&gt;.
096. \*CanbeoverriddeninsubclassestoprovidecustomTimersubclasses.
097. \*@paramdaemonwhethertocreateaTimerthatrunsasdaemonthread
098. \*@returnanewTimerinstance
099. \*@see#afterPropertiesSet()
100. \*@seejava.util.Timer#Timer(boolean)
101. \*/
102. **protected**TimercreateTimer(**boolean**daemon){
103. **return****new**Timer(daemon);
104. }
105. **public**ObjectgetObject(){
106. **return****this**.timer;
107. }
108. **public**ClassgetObjectType(){
109. **return**Timer.**class**;
110. }
111. **public****boolean**isSingleton(){
112. **return****true**;
113. }
114. /\**
115. \*CanceltheTimeronbeanfactoryshutdown,stoppingallscheduledtasks.
116. \*@seejava.util.Timer#cancel()
117. \*/
118. **public****void**destroy(){
119. logger.info("CancellingTimer");
120. **this**.timer.cancel();
121. }
122. }

这个类就是运行我们任务的类了，我们可以定制N个任务，只需要塞到这里就ok了