Spring定时器的两种实现方式一(timer)

有两种流行Spring定时器配置:Java的Timer类和OpenSymphony的Quartz。

1.Java Timer定时

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

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

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

xml 代码
  1. <beanid="infoCenterAutoBuildTask"
  2. class="com.teesoo.teanet.scheduling.InfoCenterAutoBuildTask">
  3. <propertyname="baseService"ref="baseService"/>
  4. <propertyname="htmlCreator"ref="htmlCreator"/>
  5. </bean>
  6. <beanid="scheduledTask"
  7. class="org.springframework.scheduling.timer.ScheduledTimerTask">
  8. <!--wait10secondsbeforestartingrepeatedexecution-->
  9. <propertyname="delay"value="10000"/>
  10. <!--runevery50seconds-->
  11. <propertyname="period"value="1000000"/>
  12. <propertyname="timerTask"ref="infoCenterAutoBuildTask"/>
  13. </bean>
  14. <beanid="timerFactory"class="org.springframework.scheduling.timer.TimerFactoryBean">
  15. <propertyname="scheduledTimerTasks">
  16. <list>
  17. <!--seetheexampleabove-->
  18. <refbean="scheduledTask"/>
  19. </list>
  20. </property>
  21. </bean>

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

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

java 代码
  1. BaseTaskextendsjava.util.TimerTask{
  2. //用户只需要实现这个方面,把自己的任务放到这里
  3. publicvoidrun(){
  4. }
  5. }

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

java 代码
  1. /*
  2. *Copyright2002-2005theoriginalauthororauthors.
  3. *
  4. *LicensedundertheApacheLicense,Version2.0(the"License");
  5. *youmaynotusethisfileexceptincompliancewiththeLicense.
  6. *YoumayobtainacopyoftheLicenseat
  7. *
  8. *http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. *Unlessrequiredbyapplicablelaworagreedtoinwriting,software
  11. *distributedundertheLicenseisdistributedonan"ASIS"BASIS,
  12. *WITHOUTWARRANTIESORCONDITIONSOFANYKIND,eitherexpressorimplied.
  13. *SeetheLicenseforthespecificlanguagegoverningpermissionsand
  14. *limitationsundertheLicense.
  15. */
  16. packageorg.springframework.scheduling.timer;
  17. importjava.util.TimerTask;
  18. /**
  19. *JavaBeanthatdescribesascheduledTimerTask,consistingof
  20. *theTimerTaskitself(oraRunnabletocreateaTimerTaskfor)
  21. *andadelayplusperiod.Periodneedstobespecified;
  22. *thereisnopointinadefaultforit.
  23. *
  24. *<p>TheJDKTimerdoesnotoffermoresophisticatedscheduling
  25. *optionssuchascronexpressions.ConsiderusingQuartzfor
  26. *suchadvancedneeds.
  27. *
  28. *<p>NotethatTimerusesaTimerTaskinstancethatisshared
  29. *betweenrepeatedexecutions,incontrasttoQuartzwhich
  30. *instantiatesanewJobforeachexecution.
  31. *
  32. *@authorJuergenHoeller
  33. *@since19.02.2004
  34. *@seejava.util.TimerTask
  35. *@seejava.util.Timer#schedule(TimerTask,long,long)
  36. *@seejava.util.Timer#scheduleAtFixedRate(TimerTask,long,long)
  37. */
  38. publicclassScheduledTimerTask{
  39. privateTimerTasktimerTask;
  40. privatelongdelay=0;
  41. privatelongperiod=0;
  42. privatebooleanfixedRate=false;
  43. /**
  44. *CreateanewScheduledTimerTask,
  45. *tobepopulatedviabeanproperties.
  46. *@see#setTimerTask
  47. *@see#setDelay
  48. *@see#setPeriod
  49. *@see#setFixedRate
  50. */
  51. publicScheduledTimerTask(){
  52. }
  53. /**
  54. *CreateanewScheduledTimerTask,withdefault
  55. *one-timeexecutionwithoutdelay.
  56. *@paramtimerTasktheTimerTasktoschedule
  57. */
  58. publicScheduledTimerTask(TimerTasktimerTask){
  59. this.timerTask=timerTask;
  60. }
  61. /**
  62. *CreateanewScheduledTimerTask,withdefault
  63. *one-timeexecutionwiththegivendelay.
  64. *@paramtimerTasktheTimerTasktoschedule
  65. *@paramdelaythedelaybeforestartingthetaskforthefirsttime(ms)
  66. */
  67. publicScheduledTimerTask(TimerTasktimerTask,longdelay){
  68. this.timerTask=timerTask;
  69. this.delay=delay;
  70. }
  71. /**
  72. *CreateanewScheduledTimerTask.
  73. *@paramtimerTasktheTimerTasktoschedule
  74. *@paramdelaythedelaybeforestartingthetaskforthefirsttime(ms)
  75. *@paramperiodtheperiodbetweenrepeatedtaskexecutions(ms)
  76. *@paramfixedRatewhethertoscheduleasfixed-rateexecution
  77. */
  78. publicScheduledTimerTask(TimerTasktimerTask,longdelay,longperiod,booleanfixedRate){
  79. this.timerTask=timerTask;
  80. this.delay=delay;
  81. this.period=period;
  82. this.fixedRate=fixedRate;
  83. }
  84. /**
  85. *CreateanewScheduledTimerTask,withdefault
  86. *one-timeexecutionwithoutdelay.
  87. *@paramtimerTasktheRunnabletoscheduleasTimerTask
  88. */
  89. publicScheduledTimerTask(RunnabletimerTask){
  90. setRunnable(timerTask);
  91. }
  92. /**
  93. *CreateanewScheduledTimerTask,withdefault
  94. *one-timeexecutionwiththegivendelay.
  95. *@paramtimerTasktheRunnabletoscheduleasTimerTask
  96. *@paramdelaythedelaybeforestartingthetaskforthefirsttime(ms)
  97. */
  98. publicScheduledTimerTask(RunnabletimerTask,longdelay){
  99. setRunnable(timerTask);
  100. this.delay=delay;
  101. }
  102. /**
  103. *CreateanewScheduledTimerTask.
  104. *@paramtimerTasktheRunnabletoscheduleasTimerTask
  105. *@paramdelaythedelaybeforestartingthetaskforthefirsttime(ms)
  106. *@paramperiodtheperiodbetweenrepeatedtaskexecutions(ms)
  107. *@paramfixedRatewhethertoscheduleasfixed-rateexecution
  108. */
  109. publicScheduledTimerTask(RunnabletimerTask,longdelay,longperiod,booleanfixedRate){
  110. setRunnable(timerTask);
  111. this.delay=delay;
  112. this.period=period;
  113. this.fixedRate=fixedRate;
  114. }
  115. /**
  116. *SettheRunnabletoscheduleasTimerTask.
  117. *@seeDelegatingTimerTask
  118. */
  119. publicvoidsetRunnable(RunnabletimerTask){
  120. this.timerTask=newDelegatingTimerTask(timerTask);
  121. }
  122. /**
  123. *SettheTimerTasktoschedule.
  124. */
  125. publicvoidsetTimerTask(TimerTasktimerTask){
  126. this.timerTask=timerTask;
  127. }
  128. /**
  129. *ReturntheTimerTasktoschedule.
  130. */
  131. publicTimerTaskgetTimerTask(){
  132. returntimerTask;
  133. }
  134. /**
  135. *Setthedelaybeforestartingthetaskforthefirsttime,
  136. *inmilliseconds.Defaultis0,immediatelystartingthe
  137. *taskaftersuccessfulscheduling.
  138. */
  139. publicvoidsetDelay(longdelay){
  140. this.delay=delay;
  141. }
  142. /**
  143. *Returnthedelaybeforestartingthejobforthefirsttime.
  144. */
  145. publiclonggetDelay(){
  146. returndelay;
  147. }
  148. /**
  149. *Settheperiodbetweenrepeatedtaskexecutions,inmilliseconds.
  150. *Defaultis0,leadingtoone-timeexecution.Incaseofapositive
  151. *value,thetaskwillbeexecutedrepeatedly,withthegiveninterval
  152. *inbetweenexecutions.
  153. *<p>Notethatthesemanticsoftheperiodvarybetweenfixed-rate
  154. *andfixed-delayexecution.
  155. *@see#setFixedRate
  156. */
  157. publicvoidsetPeriod(longperiod){
  158. this.period=period;
  159. }
  160. /**
  161. *Returntheperiodbetweenrepeatedtaskexecutions.
  162. */
  163. publiclonggetPeriod(){
  164. returnperiod;
  165. }
  166. /**
  167. *Setwhethertoscheduleasfixed-rateexecution,ratherthan
  168. *fixed-delayexecution.Defaultis"false",i.e.fixeddelay.
  169. *<p>SeeTimerjavadocfordetailsonthoseexecutionmodes.
  170. *@seejava.util.Timer#schedule(TimerTask,long,long)
  171. *@seejava.util.Timer#scheduleAtFixedRate(TimerTask,long,long)
  172. */
  173. publicvoidsetFixedRate(booleanfixedRate){
  174. this.fixedRate=fixedRate;
  175. }
  176. /**
  177. *Returnwhethertoscheduleasfixed-rateexecution.
  178. */
  179. publicbooleanisFixedRate(){
  180. returnfixedRate;
  181. }
  182. }

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

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

java 代码
  1. /*
  2. *Copyright2002-2006theoriginalauthororauthors.
  3. *
  4. *LicensedundertheApacheLicense,Version2.0(the"License");
  5. *youmaynotusethisfileexceptincompliancewiththeLicense.
  6. *YoumayobtainacopyoftheLicenseat
  7. *
  8. *http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. *Unlessrequiredbyapplicablelaworagreedtoinwriting,software
  11. *distributedundertheLicenseisdistributedonan"ASIS"BASIS,
  12. *WITHOUTWARRANTIESORCONDITIONSOFANYKIND,eitherexpressorimplied.
  13. *SeetheLicenseforthespecificlanguagegoverningpermissionsand
  14. *limitationsundertheLicense.
  15. */
  16. packageorg.springframework.scheduling.timer;
  17. importjava.util.Timer;
  18. importorg.apache.commons.logging.Log;
  19. importorg.apache.commons.logging.LogFactory;
  20. importorg.springframework.beans.factory.DisposableBean;
  21. importorg.springframework.beans.factory.FactoryBean;
  22. importorg.springframework.beans.factory.InitializingBean;
  23. /**
  24. *FactoryBeanthatsetsupaJDK1.3+Timerandexposesitforbeanreferences.
  25. *
  26. *<p>AllowsforregistrationofScheduledTimerTasks,automaticallystarting
  27. *theTimeroninitializationandcancellingitondestructionofthecontext.
  28. *Inscenariosthatjustrequirestaticregistrationoftasksatstartup,
  29. *thereisnoneedtoaccesstheTimerinstanceitselfinapplicationcode.
  30. *
  31. *<p>NotethatTimerusesaTimerTaskinstancethatissharedbetween
  32. *repeatedexecutions,incontrasttoQuartzwhichinstantiatesanew
  33. *Jobforeachexecution.
  34. *
  35. *@authorJuergenHoeller
  36. *@since19.02.2004
  37. *@seeScheduledTimerTask
  38. *@seejava.util.Timer
  39. *@seejava.util.TimerTask
  40. */
  41. publicclassTimerFactoryBeanimplementsFactoryBean,InitializingBean,DisposableBean{
  42. protectedfinalLoglogger=LogFactory.getLog(getClass());
  43. privateScheduledTimerTask[]scheduledTimerTasks;
  44. privatebooleandaemon=false;
  45. privateTimertimer;
  46. /**
  47. *RegisteralistofScheduledTimerTaskobjectswiththeTimerthat
  48. *thisFactoryBeancreates.DependingoneachSchedulerTimerTask's
  49. *settings,itwillberegisteredviaoneofTimer'sschedulemethods.
  50. *@seejava.util.Timer#schedule(java.util.TimerTask,long)
  51. *@seejava.util.Timer#schedule(java.util.TimerTask,long,long)
  52. *@seejava.util.Timer#scheduleAtFixedRate(java.util.TimerTask,long,long)
  53. */
  54. publicvoidsetScheduledTimerTasks(ScheduledTimerTask[]scheduledTimerTasks){
  55. this.scheduledTimerTasks=scheduledTimerTasks;
  56. }
  57. /**
  58. *Setwhetherthetimershoulduseadaemonthread,
  59. *justexecutingaslongastheapplicationitselfisrunning.
  60. *<p>Defaultis"false":Thetimerwillautomaticallygetcancelledon
  61. *destructionofthisFactoryBean.Hence,iftheapplicationshutsdown,
  62. *taskswillbydefaultfinishtheirexecution.Specify"true"foreager
  63. *shutdownofthreadsthatexecutetasks.
  64. *@seejava.util.Timer#Timer(boolean)
  65. */
  66. publicvoidsetDaemon(booleandaemon){
  67. this.daemon=daemon;
  68. }
  69. publicvoidafterPropertiesSet(){
  70. logger.info("InitializingTimer");
  71. this.timer=createTimer(this.daemon);
  72. //RegisterallScheduledTimerTasks.
  73. if(this.scheduledTimerTasks!=null){
  74. for(inti=0;i<this.scheduledTimerTasks.length;i++){
  75. ScheduledTimerTaskscheduledTask=this.scheduledTimerTasks[i];
  76. if(scheduledTask.getPeriod()>0){
  77. //repeatedtaskexecution
  78. if(scheduledTask.isFixedRate()){
  79. this.timer.scheduleAtFixedRate(
  80. scheduledTask.getTimerTask(),scheduledTask.getDelay(),scheduledTask.getPeriod());
  81. }
  82. else{
  83. this.timer.schedule(
  84. scheduledTask.getTimerTask(),scheduledTask.getDelay(),scheduledTask.getPeriod());
  85. }
  86. }
  87. else{
  88. //One-timetaskexecution.
  89. this.timer.schedule(scheduledTask.getTimerTask(),scheduledTask.getDelay());
  90. }
  91. }
  92. }
  93. }
  94. /**
  95. *CreateanewTimerinstance.Calledby<code>afterPropertiesSet</code>.
  96. *CanbeoverriddeninsubclassestoprovidecustomTimersubclasses.
  97. *@paramdaemonwhethertocreateaTimerthatrunsasdaemonthread
  98. *@returnanewTimerinstance
  99. *@see#afterPropertiesSet()
  100. *@seejava.util.Timer#Timer(boolean)
  101. */
  102. protectedTimercreateTimer(booleandaemon){
  103. returnnewTimer(daemon);
  104. }
  105. publicObjectgetObject(){
  106. returnthis.timer;
  107. }
  108. publicClassgetObjectType(){
  109. returnTimer.class;
  110. }
  111. publicbooleanisSingleton(){
  112. returntrue;
  113. }
  114. /**
  115. *CanceltheTimeronbeanfactoryshutdown,stoppingallscheduledtasks.
  116. *@seejava.util.Timer#cancel()
  117. */
  118. publicvoiddestroy(){
  119. logger.info("CancellingTimer");
  120. this.timer.cancel();
  121. }
  122. }

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


有两种流行Spring定时器配置:Java的Timer类和OpenSymphony的Quartz。

1.Java Timer定时

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

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

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

xml 代码
  1. <beanid="infoCenterAutoBuildTask"
  2. class="com.teesoo.teanet.scheduling.InfoCenterAutoBuildTask">
  3. <propertyname="baseService"ref="baseService"/>
  4. <propertyname="htmlCreator"ref="htmlCreator"/>
  5. </bean>
  6. <beanid="scheduledTask"
  7. class="org.springframework.scheduling.timer.ScheduledTimerTask">
  8. <!--wait10secondsbeforestartingrepeatedexecution-->
  9. <propertyname="delay"value="10000"/>
  10. <!--runevery50seconds-->
  11. <propertyname="period"value="1000000"/>
  12. <propertyname="timerTask"ref="infoCenterAutoBuildTask"/>
  13. </bean>
  14. <beanid="timerFactory"class="org.springframework.scheduling.timer.TimerFactoryBean">
  15. <propertyname="scheduledTimerTasks">
  16. <list>
  17. <!--seetheexampleabove-->
  18. <refbean="scheduledTask"/>
  19. </list>
  20. </property>
  21. </bean>

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

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

java 代码
  1. BaseTaskextendsjava.util.TimerTask{
  2. //用户只需要实现这个方面,把自己的任务放到这里
  3. publicvoidrun(){
  4. }
  5. }

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

java 代码
  1. /*
  2. *Copyright2002-2005theoriginalauthororauthors.
  3. *
  4. *LicensedundertheApacheLicense,Version2.0(the"License");
  5. *youmaynotusethisfileexceptincompliancewiththeLicense.
  6. *YoumayobtainacopyoftheLicenseat
  7. *
  8. *http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. *Unlessrequiredbyapplicablelaworagreedtoinwriting,software
  11. *distributedundertheLicenseisdistributedonan"ASIS"BASIS,
  12. *WITHOUTWARRANTIESORCONDITIONSOFANYKIND,eitherexpressorimplied.
  13. *SeetheLicenseforthespecificlanguagegoverningpermissionsand
  14. *limitationsundertheLicense.
  15. */
  16. packageorg.springframework.scheduling.timer;
  17. importjava.util.TimerTask;
  18. /**
  19. *JavaBeanthatdescribesascheduledTimerTask,consistingof
  20. *theTimerTaskitself(oraRunnabletocreateaTimerTaskfor)
  21. *andadelayplusperiod.Periodneedstobespecified;
  22. *thereisnopointinadefaultforit.
  23. *
  24. *<p>TheJDKTimerdoesnotoffermoresophisticatedscheduling
  25. *optionssuchascronexpressions.ConsiderusingQuartzfor
  26. *suchadvancedneeds.
  27. *
  28. *<p>NotethatTimerusesaTimerTaskinstancethatisshared
  29. *betweenrepeatedexecutions,incontrasttoQuartzwhich
  30. *instantiatesanewJobforeachexecution.
  31. *
  32. *@authorJuergenHoeller
  33. *@since19.02.2004
  34. *@seejava.util.TimerTask
  35. *@seejava.util.Timer#schedule(TimerTask,long,long)
  36. *@seejava.util.Timer#scheduleAtFixedRate(TimerTask,long,long)
  37. */
  38. publicclassScheduledTimerTask{
  39. privateTimerTasktimerTask;
  40. privatelongdelay=0;
  41. privatelongperiod=0;
  42. privatebooleanfixedRate=false;
  43. /**
  44. *CreateanewScheduledTimerTask,
  45. *tobepopulatedviabeanproperties.
  46. *@see#setTimerTask
  47. *@see#setDelay
  48. *@see#setPeriod
  49. *@see#setFixedRate
  50. */
  51. publicScheduledTimerTask(){
  52. }
  53. /**
  54. *CreateanewScheduledTimerTask,withdefault
  55. *one-timeexecutionwithoutdelay.
  56. *@paramtimerTasktheTimerTasktoschedule
  57. */
  58. publicScheduledTimerTask(TimerTasktimerTask){
  59. this.timerTask=timerTask;
  60. }
  61. /**
  62. *CreateanewScheduledTimerTask,withdefault
  63. *one-timeexecutionwiththegivendelay.
  64. *@paramtimerTasktheTimerTasktoschedule
  65. *@paramdelaythedelaybeforestartingthetaskforthefirsttime(ms)
  66. */
  67. publicScheduledTimerTask(TimerTasktimerTask,longdelay){
  68. this.timerTask=timerTask;
  69. this.delay=delay;
  70. }
  71. /**
  72. *CreateanewScheduledTimerTask.
  73. *@paramtimerTasktheTimerTasktoschedule
  74. *@paramdelaythedelaybeforestartingthetaskforthefirsttime(ms)
  75. *@paramperiodtheperiodbetweenrepeatedtaskexecutions(ms)
  76. *@paramfixedRatewhethertoscheduleasfixed-rateexecution
  77. */
  78. publicScheduledTimerTask(TimerTasktimerTask,longdelay,longperiod,booleanfixedRate){
  79. this.timerTask=timerTask;
  80. this.delay=delay;
  81. this.period=period;
  82. this.fixedRate=fixedRate;
  83. }
  84. /**
  85. *CreateanewScheduledTimerTask,withdefault
  86. *one-timeexecutionwithoutdelay.
  87. *@paramtimerTasktheRunnabletoscheduleasTimerTask
  88. */
  89. publicScheduledTimerTask(RunnabletimerTask){
  90. setRunnable(timerTask);
  91. }
  92. /**
  93. *CreateanewScheduledTimerTask,withdefault
  94. *one-timeexecutionwiththegivendelay.
  95. *@paramtimerTasktheRunnabletoscheduleasTimerTask
  96. *@paramdelaythedelaybeforestartingthetaskforthefirsttime(ms)
  97. */
  98. publicScheduledTimerTask(RunnabletimerTask,longdelay){
  99. setRunnable(timerTask);
  100. this.delay=delay;
  101. }
  102. /**
  103. *CreateanewScheduledTimerTask.
  104. *@paramtimerTasktheRunnabletoscheduleasTimerTask
  105. *@paramdelaythedelaybeforestartingthetaskforthefirsttime(ms)
  106. *@paramperiodtheperiodbetweenrepeatedtaskexecutions(ms)
  107. *@paramfixedRatewhethertoscheduleasfixed-rateexecution
  108. */
  109. publicScheduledTimerTask(RunnabletimerTask,longdelay,longperiod,booleanfixedRate){
  110. setRunnable(timerTask);
  111. this.delay=delay;
  112. this.period=period;
  113. this.fixedRate=fixedRate;
  114. }
  115. /**
  116. *SettheRunnabletoscheduleasTimerTask.
  117. *@seeDelegatingTimerTask
  118. */
  119. publicvoidsetRunnable(RunnabletimerTask){
  120. this.timerTask=newDelegatingTimerTask(timerTask);
  121. }
  122. /**
  123. *SettheTimerTasktoschedule.
  124. */
  125. publicvoidsetTimerTask(TimerTasktimerTask){
  126. this.timerTask=timerTask;
  127. }
  128. /**
  129. *ReturntheTimerTasktoschedule.
  130. */
  131. publicTimerTaskgetTimerTask(){
  132. returntimerTask;
  133. }
  134. /**
  135. *Setthedelaybeforestartingthetaskforthefirsttime,
  136. *inmilliseconds.Defaultis0,immediatelystartingthe
  137. *taskaftersuccessfulscheduling.
  138. */
  139. publicvoidsetDelay(longdelay){
  140. this.delay=delay;
  141. }
  142. /**
  143. *Returnthedelaybeforestartingthejobforthefirsttime.
  144. */
  145. publiclonggetDelay(){
  146. returndelay;
  147. }
  148. /**
  149. *Settheperiodbetweenrepeatedtaskexecutions,inmilliseconds.
  150. *Defaultis0,leadingtoone-timeexecution.Incaseofapositive
  151. *value,thetaskwillbeexecutedrepeatedly,withthegiveninterval
  152. *inbetweenexecutions.
  153. *<p>Notethatthesemanticsoftheperiodvarybetweenfixed-rate
  154. *andfixed-delayexecution.
  155. *@see#setFixedRate
  156. */
  157. publicvoidsetPeriod(longperiod){
  158. this.period=period;
  159. }
  160. /**
  161. *Returntheperiodbetweenrepeatedtaskexecutions.
  162. */
  163. publiclonggetPeriod(){
  164. returnperiod;
  165. }
  166. /**
  167. *Setwhethertoscheduleasfixed-rateexecution,ratherthan
  168. *fixed-delayexecution.Defaultis"false",i.e.fixeddelay.
  169. *<p>SeeTimerjavadocfordetailsonthoseexecutionmodes.
  170. *@seejava.util.Timer#schedule(TimerTask,long,long)
  171. *@seejava.util.Timer#scheduleAtFixedRate(TimerTask,long,long)
  172. */
  173. publicvoidsetFixedRate(booleanfixedRate){
  174. this.fixedRate=fixedRate;
  175. }
  176. /**
  177. *Returnwhethertoscheduleasfixed-rateexecution.
  178. */
  179. publicbooleanisFixedRate(){
  180. returnfixedRate;
  181. }
  182. }

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

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

java 代码
  1. /*
  2. *Copyright2002-2006theoriginalauthororauthors.
  3. *
  4. *LicensedundertheApacheLicense,Version2.0(the"License");
  5. *youmaynotusethisfileexceptincompliancewiththeLicense.
  6. *YoumayobtainacopyoftheLicenseat
  7. *
  8. *http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. *Unlessrequiredbyapplicablelaworagreedtoinwriting,software
  11. *distributedundertheLicenseisdistributedonan"ASIS"BASIS,
  12. *WITHOUTWARRANTIESORCONDITIONSOFANYKIND,eitherexpressorimplied.
  13. *SeetheLicenseforthespecificlanguagegoverningpermissionsand
  14. *limitationsundertheLicense.
  15. */
  16. packageorg.springframework.scheduling.timer;
  17. importjava.util.Timer;
  18. importorg.apache.commons.logging.Log;
  19. importorg.apache.commons.logging.LogFactory;
  20. importorg.springframework.beans.factory.DisposableBean;
  21. importorg.springframework.beans.factory.FactoryBean;
  22. importorg.springframework.beans.factory.InitializingBean;
  23. /**
  24. *FactoryBeanthatsetsupaJDK1.3+Timerandexposesitforbeanreferences.
  25. *
  26. *<p>AllowsforregistrationofScheduledTimerTasks,automaticallystarting
  27. *theTimeroninitializationandcancellingitondestructionofthecontext.
  28. *Inscenariosthatjustrequirestaticregistrationoftasksatstartup,
  29. *thereisnoneedtoaccesstheTimerinstanceitselfinapplicationcode.
  30. *
  31. *<p>NotethatTimerusesaTimerTaskinstancethatissharedbetween
  32. *repeatedexecutions,incontrasttoQuartzwhichinstantiatesanew
  33. *Jobforeachexecution.
  34. *
  35. *@authorJuergenHoeller
  36. *@since19.02.2004
  37. *@seeScheduledTimerTask
  38. *@seejava.util.Timer
  39. *@seejava.util.TimerTask
  40. */
  41. publicclassTimerFactoryBeanimplementsFactoryBean,InitializingBean,DisposableBean{
  42. protectedfinalLoglogger=LogFactory.getLog(getClass());
  43. privateScheduledTimerTask[]scheduledTimerTasks;
  44. privatebooleandaemon=false;
  45. privateTimertimer;
  46. /**
  47. *RegisteralistofScheduledTimerTaskobjectswiththeTimerthat
  48. *thisFactoryBeancreates.DependingoneachSchedulerTimerTask's
  49. *settings,itwillberegisteredviaoneofTimer'sschedulemethods.
  50. *@seejava.util.Timer#schedule(java.util.TimerTask,long)
  51. *@seejava.util.Timer#schedule(java.util.TimerTask,long,long)
  52. *@seejava.util.Timer#scheduleAtFixedRate(java.util.TimerTask,long,long)
  53. */
  54. publicvoidsetScheduledTimerTasks(ScheduledTimerTask[]scheduledTimerTasks){
  55. this.scheduledTimerTasks=scheduledTimerTasks;
  56. }
  57. /**
  58. *Setwhetherthetimershoulduseadaemonthread,
  59. *justexecutingaslongastheapplicationitselfisrunning.
  60. *<p>Defaultis"false":Thetimerwillautomaticallygetcancelledon
  61. *destructionofthisFactoryBean.Hence,iftheapplicationshutsdown,
  62. *taskswillbydefaultfinishtheirexecution.Specify"true"foreager
  63. *shutdownofthreadsthatexecutetasks.
  64. *@seejava.util.Timer#Timer(boolean)
  65. */
  66. publicvoidsetDaemon(booleandaemon){
  67. this.daemon=daemon;
  68. }
  69. publicvoidafterPropertiesSet(){
  70. logger.info("InitializingTimer");
  71. this.timer=createTimer(this.daemon);
  72. //RegisterallScheduledTimerTasks.
  73. if(this.scheduledTimerTasks!=null){
  74. for(inti=0;i<this.scheduledTimerTasks.length;i++){
  75. ScheduledTimerTaskscheduledTask=this.scheduledTimerTasks[i];
  76. if(scheduledTask.getPeriod()>0){
  77. //repeatedtaskexecution
  78. if(scheduledTask.isFixedRate()){
  79. this.timer.scheduleAtFixedRate(
  80. scheduledTask.getTimerTask(),scheduledTask.getDelay(),scheduledTask.getPeriod());
  81. }
  82. else{
  83. this.timer.schedule(
  84. scheduledTask.getTimerTask(),scheduledTask.getDelay(),scheduledTask.getPeriod());
  85. }
  86. }
  87. else{
  88. //One-timetaskexecution.
  89. this.timer.schedule(scheduledTask.getTimerTask(),scheduledTask.getDelay());
  90. }
  91. }
  92. }
  93. }
  94. /**
  95. *CreateanewTimerinstance.Calledby<code>afterPropertiesSet</code>.
  96. *CanbeoverriddeninsubclassestoprovidecustomTimersubclasses.
  97. *@paramdaemonwhethertocreateaTimerthatrunsasdaemonthread
  98. *@returnanewTimerinstance
  99. *@see#afterPropertiesSet()
  100. *@seejava.util.Timer#Timer(boolean)
  101. */
  102. protectedTimercreateTimer(booleandaemon){
  103. returnnewTimer(daemon);
  104. }
  105. publicObjectgetObject(){
  106. returnthis.timer;
  107. }
  108. publicClassgetObjectType(){
  109. returnTimer.class;
  110. }
  111. publicbooleanisSingleton(){
  112. returntrue;
  113. }
  114. /**
  115. *CanceltheTimeronbeanfactoryshutdown,stoppingallscheduledtasks.
  116. *@seejava.util.Timer#cancel()
  117. */
  118. publicvoiddestroy(){
  119. logger.info("CancellingTimer");
  120. this.timer.cancel();
  121. }
  122. }

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值