`
txf2004
  • 浏览: 6911302 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

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定时器 Spring定时器的两种实现方式Java的Timer类和OpenSymphony的Quartz。

    spring定时器Spring定时器的两种实现方式Java的Timer类和OpenSymphony的Quartz。

    JAVA中 Spring定时器的两种实现方式

    本文向您介绍Spring定时器的两种实现方式,包括Java Timer定时和Quartz定时器,两种Spring定时器的实现方式各有优点,可结合具体项目考虑是否采用。

    Spring定时器实例(Java的Timer类和OpenSymphony的Quartz)

    Spring两种定时器实例配置:Java的TimerTask类和OpenSymphony的Quartz。包含5种配置方式:timer普通定时器、timer特定方法定时器、quartz简单定时器、quartz精确定时器、quartz特定方法定时器。简单实用,一看就会。

    SPRING 定时器的使用

    并非应用系统中发生的所有事情都是由用户的动作引起的。...在Spring中有两种流行配置:Java的Timer类和OpenSymphony的Quartz来执行调度任务。下面以给商丘做的接口集抄900到中间库的日冻结数据传输为例:

    基于Java实现的几种定时任务的方式

    Spring自带了一套定时任务工具Spring-Task,可以把它看成是一个轻量级的Quartz,使用起来十分简单,除Spring相关的包外不需要额外的包,支持注解和配置文件两种形式。通常情况下在Spring体系内,针对简单的定时任务...

    java 中Spring task定时任务的深入理解

    在工作中有用到spring task作为定时任务的处理,spring通过接口TaskExecutor和TaskScheduler这两个接口的方式为异步定时任务提供了一种抽象。这就意味着spring容许你使用其他的定时任务框架,当然spring自身也提供了...

    【百占百胜】-三创比赛,学习定时器的心路历程and基于spring-task实现定时任务简单介绍

    在我了解的过程中发现java实现定时任务有四种,首先是jdk自带的两个Timer,ScheduledThreadPoolExecutor,后者是jdk1.5提出的,因为这个Timer毛病着实有点多,像什么单线程,出问题了其他任务也执

    JAVA上百实例源码以及开源项目

     //给客户发一个感谢消息,消息驱动Bean必须实现两个接口MessageDrivenBean和MessageListener  在对象创建的过程中将被容器调用,onMessage函数方法接收消息参数,将其强制转型为合适的消息类型,同时打印出消息...

    JAVA上百实例源码以及开源项目源代码

     //给客户发一个感谢消息,消息驱动Bean必须实现两个接口MessageDrivenBean和MessageListener  在对象创建的过程中将被容器调用,onMessage函数方法接收消息参数,将其强制转型为合适的消息类型,同时打印出消息...

Global site tag (gtag.js) - Google Analytics