有兩種流行Spring定時器配置:Java的Timer類和OpenSymphony的Quartz。
1.Java Timer定時
相信做軟件的朋友都有這樣的經歷,我的軟件是不是少了點什麼東西呢?比如定時任務啊,
就拿新聞發佈系統來說,如果新聞的數據更新太快,勢必涉及一個問題,這些新聞不能由人工的去發佈,應該讓系統自己發佈,這就需要用到定時定製任務了,以前定製任務無非就是設計一個Thread,並且設置運行時間片,讓它到了那個時間執行一次,就ok了,讓系統啓動的時候啓動它,想來也夠簡單的。不過有了spring,我想這事情就更簡單了。
看看spring的配置文件,想來就只有這個配置文件了
- <beanid="infoCenterAutoBuildTask"
- class="com.teesoo.teanet.scheduling.InfoCenterAutoBuildTask">
- <propertyname="baseService"ref="baseService"/>
- <propertyname="htmlCreator"ref="htmlCreator"/>
- </bean>
- <beanid="scheduledTask"
- class="org.springframework.scheduling.timer.ScheduledTimerTask">
- <!--wait10secondsbeforestartingrepeatedexecution-->
- <propertyname="delay"value="10000"/>
- <!--runevery50seconds-->
- <propertyname="period"value="1000000"/>
- <propertyname="timerTask"ref="infoCenterAutoBuildTask"/>
- </bean>
- <beanid="timerFactory"class="org.springframework.scheduling.timer.TimerFactoryBean">
- <propertyname="scheduledTimerTasks">
- <list>
- <!--seetheexampleabove-->
- <refbean="scheduledTask"/>
- </list>
- </property>
- </bean>
上面三個配置文件中只有一個配置文件是涉及到您自己的class的,其他的都是spring的類。很簡單吧
我們只需要涉及一個class讓他繼承java.util.TimerTask;
- BaseTaskextendsjava.util.TimerTask{
- //用戶只需要實現這個方面,把自己的任務放到這裏
- publicvoidrun(){
- }
- }
下面讓我們來看看 spring的源代碼
- /*
- *Copyright2002-2005theoriginalauthororauthors.
- *
- *LicensedundertheApacheLicense,Version2.0(the"License");
- *youmaynotusethisfileexceptincompliancewiththeLicense.
- *YoumayobtainacopyoftheLicenseat
- *
- *http://www.apache.org/licenses/LICENSE-2.0
- *
- *Unlessrequiredbyapplicablelaworagreedtoinwriting,software
- *distributedundertheLicenseisdistributedonan"ASIS"BASIS,
- *WITHOUTWARRANTIESORCONDITIONSOFANYKIND,eitherexpressorimplied.
- *SeetheLicenseforthespecificlanguagegoverningpermissionsand
- *limitationsundertheLicense.
- */
- packageorg.springframework.scheduling.timer;
- importjava.util.TimerTask;
- /**
- *JavaBeanthatdescribesascheduledTimerTask,consistingof
- *theTimerTaskitself(oraRunnabletocreateaTimerTaskfor)
- *andadelayplusperiod.Periodneedstobespecified;
- *thereisnopointinadefaultforit.
- *
- *<p>TheJDKTimerdoesnotoffermoresophisticatedscheduling
- *optionssuchascronexpressions.ConsiderusingQuartzfor
- *suchadvancedneeds.
- *
- *<p>NotethatTimerusesaTimerTaskinstancethatisshared
- *betweenrepeatedexecutions,incontrasttoQuartzwhich
- *instantiatesanewJobforeachexecution.
- *
- *@authorJuergenHoeller
- *@since19.02.2004
- *@seejava.util.TimerTask
- *@seejava.util.Timer#schedule(TimerTask,long,long)
- *@seejava.util.Timer#scheduleAtFixedRate(TimerTask,long,long)
- */
- publicclassScheduledTimerTask{
- privateTimerTasktimerTask;
- privatelongdelay=0;
- privatelongperiod=0;
- privatebooleanfixedRate=false;
- /**
- *CreateanewScheduledTimerTask,
- *tobepopulatedviabeanproperties.
- *@see#setTimerTask
- *@see#setDelay
- *@see#setPeriod
- *@see#setFixedRate
- */
- publicScheduledTimerTask(){
- }
- /**
- *CreateanewScheduledTimerTask,withdefault
- *one-timeexecutionwithoutdelay.
- *@paramtimerTasktheTimerTasktoschedule
- */
- publicScheduledTimerTask(TimerTasktimerTask){
- this.timerTask=timerTask;
- }
- /**
- *CreateanewScheduledTimerTask,withdefault
- *one-timeexecutionwiththegivendelay.
- *@paramtimerTasktheTimerTasktoschedule
- *@paramdelaythedelaybeforestartingthetaskforthefirsttime(ms)
- */
- publicScheduledTimerTask(TimerTasktimerTask,longdelay){
- this.timerTask=timerTask;
- this.delay=delay;
- }
- /**
- *CreateanewScheduledTimerTask.
- *@paramtimerTasktheTimerTasktoschedule
- *@paramdelaythedelaybeforestartingthetaskforthefirsttime(ms)
- *@paramperiodtheperiodbetweenrepeatedtaskexecutions(ms)
- *@paramfixedRatewhethertoscheduleasfixed-rateexecution
- */
- publicScheduledTimerTask(TimerTasktimerTask,longdelay,longperiod,booleanfixedRate){
- this.timerTask=timerTask;
- this.delay=delay;
- this.period=period;
- this.fixedRate=fixedRate;
- }
- /**
- *CreateanewScheduledTimerTask,withdefault
- *one-timeexecutionwithoutdelay.
- *@paramtimerTasktheRunnabletoscheduleasTimerTask
- */
- publicScheduledTimerTask(RunnabletimerTask){
- setRunnable(timerTask);
- }
- /**
- *CreateanewScheduledTimerTask,withdefault
- *one-timeexecutionwiththegivendelay.
- *@paramtimerTasktheRunnabletoscheduleasTimerTask
- *@paramdelaythedelaybeforestartingthetaskforthefirsttime(ms)
- */
- publicScheduledTimerTask(RunnabletimerTask,longdelay){
- setRunnable(timerTask);
- this.delay=delay;
- }
- /**
- *CreateanewScheduledTimerTask.
- *@paramtimerTasktheRunnabletoscheduleasTimerTask
- *@paramdelaythedelaybeforestartingthetaskforthefirsttime(ms)
- *@paramperiodtheperiodbetweenrepeatedtaskexecutions(ms)
- *@paramfixedRatewhethertoscheduleasfixed-rateexecution
- */
- publicScheduledTimerTask(RunnabletimerTask,longdelay,longperiod,booleanfixedRate){
- setRunnable(timerTask);
- this.delay=delay;
- this.period=period;
- this.fixedRate=fixedRate;
- }
- /**
- *SettheRunnabletoscheduleasTimerTask.
- *@seeDelegatingTimerTask
- */
- publicvoidsetRunnable(RunnabletimerTask){
- this.timerTask=newDelegatingTimerTask(timerTask);
- }
- /**
- *SettheTimerTasktoschedule.
- */
- publicvoidsetTimerTask(TimerTasktimerTask){
- this.timerTask=timerTask;
- }
- /**
- *ReturntheTimerTasktoschedule.
- */
- publicTimerTaskgetTimerTask(){
- returntimerTask;
- }
- /**
- *Setthedelaybeforestartingthetaskforthefirsttime,
- *inmilliseconds.Defaultis0,immediatelystartingthe
- *taskaftersuccessfulscheduling.
- */
- publicvoidsetDelay(longdelay){
- this.delay=delay;
- }
- /**
- *Returnthedelaybeforestartingthejobforthefirsttime.
- */
- publiclonggetDelay(){
- returndelay;
- }
- /**
- *Settheperiodbetweenrepeatedtaskexecutions,inmilliseconds.
- *Defaultis0,leadingtoone-timeexecution.Incaseofapositive
- *value,thetaskwillbeexecutedrepeatedly,withthegiveninterval
- *inbetweenexecutions.
- *<p>Notethatthesemanticsoftheperiodvarybetweenfixed-rate
- *andfixed-delayexecution.
- *@see#setFixedRate
- */
- publicvoidsetPeriod(longperiod){
- this.period=period;
- }
- /**
- *Returntheperiodbetweenrepeatedtaskexecutions.
- */
- publiclonggetPeriod(){
- returnperiod;
- }
- /**
- *Setwhethertoscheduleasfixed-rateexecution,ratherthan
- *fixed-delayexecution.Defaultis"false",i.e.fixeddelay.
- *<p>SeeTimerjavadocfordetailsonthoseexecutionmodes.
- *@seejava.util.Timer#schedule(TimerTask,long,long)
- *@seejava.util.Timer#scheduleAtFixedRate(TimerTask,long,long)
- */
- publicvoidsetFixedRate(booleanfixedRate){
- this.fixedRate=fixedRate;
- }
- /**
- *Returnwhethertoscheduleasfixed-rateexecution.
- */
- publicbooleanisFixedRate(){
- returnfixedRate;
- }
- }
說實話這個類也沒什麼,只是簡單的包裝了我們的timertask,裏面也就只有幾個屬性,一個是時間片,一個是任務等。
真正運行我們的任務的類是:
- /*
- *Copyright2002-2006theoriginalauthororauthors.
- *
- *LicensedundertheApacheLicense,Version2.0(the"License");
- *youmaynotusethisfileexceptincompliancewiththeLicense.
- *YoumayobtainacopyoftheLicenseat
- *
- *http://www.apache.org/licenses/LICENSE-2.0
- *
- *Unlessrequiredbyapplicablelaworagreedtoinwriting,software
- *distributedundertheLicenseisdistributedonan"ASIS"BASIS,
- *WITHOUTWARRANTIESORCONDITIONSOFANYKIND,eitherexpressorimplied.
- *SeetheLicenseforthespecificlanguagegoverningpermissionsand
- *limitationsundertheLicense.
- */
- packageorg.springframework.scheduling.timer;
- importjava.util.Timer;
- importorg.apache.commons.logging.Log;
- importorg.apache.commons.logging.LogFactory;
- importorg.springframework.beans.factory.DisposableBean;
- importorg.springframework.beans.factory.FactoryBean;
- importorg.springframework.beans.factory.InitializingBean;
- /**
- *FactoryBeanthatsetsupaJDK1.3+Timerandexposesitforbeanreferences.
- *
- *<p>AllowsforregistrationofScheduledTimerTasks,automaticallystarting
- *theTimeroninitializationandcancellingitondestructionofthecontext.
- *Inscenariosthatjustrequirestaticregistrationoftasksatstartup,
- *thereisnoneedtoaccesstheTimerinstanceitselfinapplicationcode.
- *
- *<p>NotethatTimerusesaTimerTaskinstancethatissharedbetween
- *repeatedexecutions,incontrasttoQuartzwhichinstantiatesanew
- *Jobforeachexecution.
- *
- *@authorJuergenHoeller
- *@since19.02.2004
- *@seeScheduledTimerTask
- *@seejava.util.Timer
- *@seejava.util.TimerTask
- */
- publicclassTimerFactoryBeanimplementsFactoryBean,InitializingBean,DisposableBean{
- protectedfinalLoglogger=LogFactory.getLog(getClass());
- privateScheduledTimerTask[]scheduledTimerTasks;
- privatebooleandaemon=false;
- privateTimertimer;
- /**
- *RegisteralistofScheduledTimerTaskobjectswiththeTimerthat
- *thisFactoryBeancreates.DependingoneachSchedulerTimerTask's
- *settings,itwillberegisteredviaoneofTimer'sschedulemethods.
- *@seejava.util.Timer#schedule(java.util.TimerTask,long)
- *@seejava.util.Timer#schedule(java.util.TimerTask,long,long)
- *@seejava.util.Timer#scheduleAtFixedRate(java.util.TimerTask,long,long)
- */
- publicvoidsetScheduledTimerTasks(ScheduledTimerTask[]scheduledTimerTasks){
- this.scheduledTimerTasks=scheduledTimerTasks;
- }
- /**
- *Setwhetherthetimershoulduseadaemonthread,
- *justexecutingaslongastheapplicationitselfisrunning.
- *<p>Defaultis"false":Thetimerwillautomaticallygetcancelledon
- *destructionofthisFactoryBean.Hence,iftheapplicationshutsdown,
- *taskswillbydefaultfinishtheirexecution.Specify"true"foreager
- *shutdownofthreadsthatexecutetasks.
- *@seejava.util.Timer#Timer(boolean)
- */
- publicvoidsetDaemon(booleandaemon){
- this.daemon=daemon;
- }
- publicvoidafterPropertiesSet(){
- logger.info("InitializingTimer");
- this.timer=createTimer(this.daemon);
- //RegisterallScheduledTimerTasks.
- if(this.scheduledTimerTasks!=null){
- for(inti=0;i<this.scheduledTimerTasks.length;i++){
- ScheduledTimerTaskscheduledTask=this.scheduledTimerTasks[i];
- if(scheduledTask.getPeriod()>0){
- //repeatedtaskexecution
- if(scheduledTask.isFixedRate()){
- this.timer.scheduleAtFixedRate(
- scheduledTask.getTimerTask(),scheduledTask.getDelay(),scheduledTask.getPeriod());
- }
- else{
- this.timer.schedule(
- scheduledTask.getTimerTask(),scheduledTask.getDelay(),scheduledTask.getPeriod());
- }
- }
- else{
- //One-timetaskexecution.
- this.timer.schedule(scheduledTask.getTimerTask(),scheduledTask.getDelay());
- }
- }
- }
- }
- /**
- *CreateanewTimerinstance.Calledby<code>afterPropertiesSet</code>.
- *CanbeoverriddeninsubclassestoprovidecustomTimersubclasses.
- *@paramdaemonwhethertocreateaTimerthatrunsasdaemonthread
- *@returnanewTimerinstance
- *@see#afterPropertiesSet()
- *@seejava.util.Timer#Timer(boolean)
- */
- protectedTimercreateTimer(booleandaemon){
- returnnewTimer(daemon);
- }
- publicObjectgetObject(){
- returnthis.timer;
- }
- publicClassgetObjectType(){
- returnTimer.class;
- }
- publicbooleanisSingleton(){
- returntrue;
- }
- /**
- *CanceltheTimeronbeanfactoryshutdown,stoppingallscheduledtasks.
- *@seejava.util.Timer#cancel()
- */
- publicvoiddestroy(){
- logger.info("CancellingTimer");
- this.timer.cancel();
- }
- }
這個類就是運行我們任務的類了,我們可以定製N個任務,只需要塞到這裏就ok了
有兩種流行Spring定時器配置:Java的Timer類和OpenSymphony的Quartz。
1.Java Timer定時
相信做軟件的朋友都有這樣的經歷,我的軟件是不是少了點什麼東西呢?比如定時任務啊,
就拿新聞發佈系統來說,如果新聞的數據更新太快,勢必涉及一個問題,這些新聞不能由人工的去發佈,應該讓系統自己發佈,這就需要用到定時定製任務了,以前定製任務無非就是設計一個Thread,並且設置運行時間片,讓它到了那個時間執行一次,就ok了,讓系統啓動的時候啓動它,想來也夠簡單的。不過有了spring,我想這事情就更簡單了。
看看spring的配置文件,想來就只有這個配置文件了
- <beanid="infoCenterAutoBuildTask"
- class="com.teesoo.teanet.scheduling.InfoCenterAutoBuildTask">
- <propertyname="baseService"ref="baseService"/>
- <propertyname="htmlCreator"ref="htmlCreator"/>
- </bean>
- <beanid="scheduledTask"
- class="org.springframework.scheduling.timer.ScheduledTimerTask">
- <!--wait10secondsbeforestartingrepeatedexecution-->
- <propertyname="delay"value="10000"/>
- <!--runevery50seconds-->
- <propertyname="period"value="1000000"/>
- <propertyname="timerTask"ref="infoCenterAutoBuildTask"/>
- </bean>
- <beanid="timerFactory"class="org.springframework.scheduling.timer.TimerFactoryBean">
- <propertyname="scheduledTimerTasks">
- <list>
- <!--seetheexampleabove-->
- <refbean="scheduledTask"/>
- </list>
- </property>
- </bean>
上面三個配置文件中只有一個配置文件是涉及到您自己的class的,其他的都是spring的類。很簡單吧
我們只需要涉及一個class讓他繼承java.util.TimerTask;
- BaseTaskextendsjava.util.TimerTask{
- //用戶只需要實現這個方面,把自己的任務放到這裏
- publicvoidrun(){
- }
- }
下面讓我們來看看 spring的源代碼
- /*
- *Copyright2002-2005theoriginalauthororauthors.
- *
- *LicensedundertheApacheLicense,Version2.0(the"License");
- *youmaynotusethisfileexceptincompliancewiththeLicense.
- *YoumayobtainacopyoftheLicenseat
- *
- *http://www.apache.org/licenses/LICENSE-2.0
- *
- *Unlessrequiredbyapplicablelaworagreedtoinwriting,software
- *distributedundertheLicenseisdistributedonan"ASIS"BASIS,
- *WITHOUTWARRANTIESORCONDITIONSOFANYKIND,eitherexpressorimplied.
- *SeetheLicenseforthespecificlanguagegoverningpermissionsand
- *limitationsundertheLicense.
- */
- packageorg.springframework.scheduling.timer;
- importjava.util.TimerTask;
- /**
- *JavaBeanthatdescribesascheduledTimerTask,consistingof
- *theTimerTaskitself(oraRunnabletocreateaTimerTaskfor)
- *andadelayplusperiod.Periodneedstobespecified;
- *thereisnopointinadefaultforit.
- *
- *<p>TheJDKTimerdoesnotoffermoresophisticatedscheduling
- *optionssuchascronexpressions.ConsiderusingQuartzfor
- *suchadvancedneeds.
- *
- *<p>NotethatTimerusesaTimerTaskinstancethatisshared
- *betweenrepeatedexecutions,incontrasttoQuartzwhich
- *instantiatesanewJobforeachexecution.
- *
- *@authorJuergenHoeller
- *@since19.02.2004
- *@seejava.util.TimerTask
- *@seejava.util.Timer#schedule(TimerTask,long,long)
- *@seejava.util.Timer#scheduleAtFixedRate(TimerTask,long,long)
- */
- publicclassScheduledTimerTask{
- privateTimerTasktimerTask;
- privatelongdelay=0;
- privatelongperiod=0;
- privatebooleanfixedRate=false;
- /**
- *CreateanewScheduledTimerTask,
- *tobepopulatedviabeanproperties.
- *@see#setTimerTask
- *@see#setDelay
- *@see#setPeriod
- *@see#setFixedRate
- */
- publicScheduledTimerTask(){
- }
- /**
- *CreateanewScheduledTimerTask,withdefault
- *one-timeexecutionwithoutdelay.
- *@paramtimerTasktheTimerTasktoschedule
- */
- publicScheduledTimerTask(TimerTasktimerTask){
- this.timerTask=timerTask;
- }
- /**
- *CreateanewScheduledTimerTask,withdefault
- *one-timeexecutionwiththegivendelay.
- *@paramtimerTasktheTimerTasktoschedule
- *@paramdelaythedelaybeforestartingthetaskforthefirsttime(ms)
- */
- publicScheduledTimerTask(TimerTasktimerTask,longdelay){
- this.timerTask=timerTask;
- this.delay=delay;
- }
- /**
- *CreateanewScheduledTimerTask.
- *@paramtimerTasktheTimerTasktoschedule
- *@paramdelaythedelaybeforestartingthetaskforthefirsttime(ms)
- *@paramperiodtheperiodbetweenrepeatedtaskexecutions(ms)
- *@paramfixedRatewhethertoscheduleasfixed-rateexecution
- */
- publicScheduledTimerTask(TimerTasktimerTask,longdelay,longperiod,booleanfixedRate){
- this.timerTask=timerTask;
- this.delay=delay;
- this.period=period;
- this.fixedRate=fixedRate;
- }
- /**
- *CreateanewScheduledTimerTask,withdefault
- *one-timeexecutionwithoutdelay.
- *@paramtimerTasktheRunnabletoscheduleasTimerTask
- */
- publicScheduledTimerTask(RunnabletimerTask){
- setRunnable(timerTask);
- }
- /**
- *CreateanewScheduledTimerTask,withdefault
- *one-timeexecutionwiththegivendelay.
- *@paramtimerTasktheRunnabletoscheduleasTimerTask
- *@paramdelaythedelaybeforestartingthetaskforthefirsttime(ms)
- */
- publicScheduledTimerTask(RunnabletimerTask,longdelay){
- setRunnable(timerTask);
- this.delay=delay;
- }
- /**
- *CreateanewScheduledTimerTask.
- *@paramtimerTasktheRunnabletoscheduleasTimerTask
- *@paramdelaythedelaybeforestartingthetaskforthefirsttime(ms)
- *@paramperiodtheperiodbetweenrepeatedtaskexecutions(ms)
- *@paramfixedRatewhethertoscheduleasfixed-rateexecution
- */
- publicScheduledTimerTask(RunnabletimerTask,longdelay,longperiod,booleanfixedRate){
- setRunnable(timerTask);
- this.delay=delay;
- this.period=period;
- this.fixedRate=fixedRate;
- }
- /**
- *SettheRunnabletoscheduleasTimerTask.
- *@seeDelegatingTimerTask
- */
- publicvoidsetRunnable(RunnabletimerTask){
- this.timerTask=newDelegatingTimerTask(timerTask);
- }
- /**
- *SettheTimerTasktoschedule.
- */
- publicvoidsetTimerTask(TimerTasktimerTask){
- this.timerTask=timerTask;
- }
- /**
- *ReturntheTimerTasktoschedule.
- */
- publicTimerTaskgetTimerTask(){
- returntimerTask;
- }
- /**
- *Setthedelaybeforestartingthetaskforthefirsttime,
- *inmilliseconds.Defaultis0,immediatelystartingthe
- *taskaftersuccessfulscheduling.
- */
- publicvoidsetDelay(longdelay){
- this.delay=delay;
- }
- /**
- *Returnthedelaybeforestartingthejobforthefirsttime.
- */
- publiclonggetDelay(){
- returndelay;
- }
- /**
- *Settheperiodbetweenrepeatedtaskexecutions,inmilliseconds.
- *Defaultis0,leadingtoone-timeexecution.Incaseofapositive
- *value,thetaskwillbeexecutedrepeatedly,withthegiveninterval
- *inbetweenexecutions.
- *<p>Notethatthesemanticsoftheperiodvarybetweenfixed-rate
- *andfixed-delayexecution.
- *@see#setFixedRate
- */
- publicvoidsetPeriod(longperiod){
- this.period=period;
- }
- /**
- *Returntheperiodbetweenrepeatedtaskexecutions.
- */
- publiclonggetPeriod(){
- returnperiod;
- }
- /**
- *Setwhethertoscheduleasfixed-rateexecution,ratherthan
- *fixed-delayexecution.Defaultis"false",i.e.fixeddelay.
- *<p>SeeTimerjavadocfordetailsonthoseexecutionmodes.
- *@seejava.util.Timer#schedule(TimerTask,long,long)
- *@seejava.util.Timer#scheduleAtFixedRate(TimerTask,long,long)
- */
- publicvoidsetFixedRate(booleanfixedRate){
- this.fixedRate=fixedRate;
- }
- /**
- *Returnwhethertoscheduleasfixed-rateexecution.
- */
- publicbooleanisFixedRate(){
- returnfixedRate;
- }
- }
說實話這個類也沒什麼,只是簡單的包裝了我們的timertask,裏面也就只有幾個屬性,一個是時間片,一個是任務等。
真正運行我們的任務的類是:
- /*
- *Copyright2002-2006theoriginalauthororauthors.
- *
- *LicensedundertheApacheLicense,Version2.0(the"License");
- *youmaynotusethisfileexceptincompliancewiththeLicense.
- *YoumayobtainacopyoftheLicenseat
- *
- *http://www.apache.org/licenses/LICENSE-2.0
- *
- *Unlessrequiredbyapplicablelaworagreedtoinwriting,software
- *distributedundertheLicenseisdistributedonan"ASIS"BASIS,
- *WITHOUTWARRANTIESORCONDITIONSOFANYKIND,eitherexpressorimplied.
- *SeetheLicenseforthespecificlanguagegoverningpermissionsand
- *limitationsundertheLicense.
- */
- packageorg.springframework.scheduling.timer;
- importjava.util.Timer;
- importorg.apache.commons.logging.Log;
- importorg.apache.commons.logging.LogFactory;
- importorg.springframework.beans.factory.DisposableBean;
- importorg.springframework.beans.factory.FactoryBean;
- importorg.springframework.beans.factory.InitializingBean;
- /**
- *FactoryBeanthatsetsupaJDK1.3+Timerandexposesitforbeanreferences.
- *
- *<p>AllowsforregistrationofScheduledTimerTasks,automaticallystarting
- *theTimeroninitializationandcancellingitondestructionofthecontext.
- *Inscenariosthatjustrequirestaticregistrationoftasksatstartup,
- *thereisnoneedtoaccesstheTimerinstanceitselfinapplicationcode.
- *
- *<p>NotethatTimerusesaTimerTaskinstancethatissharedbetween
- *repeatedexecutions,incontrasttoQuartzwhichinstantiatesanew
- *Jobforeachexecution.
- *
- *@authorJuergenHoeller
- *@since19.02.2004
- *@seeScheduledTimerTask
- *@seejava.util.Timer
- *@seejava.util.TimerTask
- */
- publicclassTimerFactoryBeanimplementsFactoryBean,InitializingBean,DisposableBean{
- protectedfinalLoglogger=LogFactory.getLog(getClass());
- privateScheduledTimerTask[]scheduledTimerTasks;
- privatebooleandaemon=false;
- privateTimertimer;
- /**
- *RegisteralistofScheduledTimerTaskobjectswiththeTimerthat
- *thisFactoryBeancreates.DependingoneachSchedulerTimerTask's
- *settings,itwillberegisteredviaoneofTimer'sschedulemethods.
- *@seejava.util.Timer#schedule(java.util.TimerTask,long)
- *@seejava.util.Timer#schedule(java.util.TimerTask,long,long)
- *@seejava.util.Timer#scheduleAtFixedRate(java.util.TimerTask,long,long)
- */
- publicvoidsetScheduledTimerTasks(ScheduledTimerTask[]scheduledTimerTasks){
- this.scheduledTimerTasks=scheduledTimerTasks;
- }
- /**
- *Setwhetherthetimershoulduseadaemonthread,
- *justexecutingaslongastheapplicationitselfisrunning.
- *<p>Defaultis"false":Thetimerwillautomaticallygetcancelledon
- *destructionofthisFactoryBean.Hence,iftheapplicationshutsdown,
- *taskswillbydefaultfinishtheirexecution.Specify"true"foreager
- *shutdownofthreadsthatexecutetasks.
- *@seejava.util.Timer#Timer(boolean)
- */
- publicvoidsetDaemon(booleandaemon){
- this.daemon=daemon;
- }
- publicvoidafterPropertiesSet(){
- logger.info("InitializingTimer");
- this.timer=createTimer(this.daemon);
- //RegisterallScheduledTimerTasks.
- if(this.scheduledTimerTasks!=null){
- for(inti=0;i<this.scheduledTimerTasks.length;i++){
- ScheduledTimerTaskscheduledTask=this.scheduledTimerTasks[i];
- if(scheduledTask.getPeriod()>0){
- //repeatedtaskexecution
- if(scheduledTask.isFixedRate()){
- this.timer.scheduleAtFixedRate(
- scheduledTask.getTimerTask(),scheduledTask.getDelay(),scheduledTask.getPeriod());
- }
- else{
- this.timer.schedule(
- scheduledTask.getTimerTask(),scheduledTask.getDelay(),scheduledTask.getPeriod());
- }
- }
- else{
- //One-timetaskexecution.
- this.timer.schedule(scheduledTask.getTimerTask(),scheduledTask.getDelay());
- }
- }
- }
- }
- /**
- *CreateanewTimerinstance.Calledby<code>afterPropertiesSet</code>.
- *CanbeoverriddeninsubclassestoprovidecustomTimersubclasses.
- *@paramdaemonwhethertocreateaTimerthatrunsasdaemonthread
- *@returnanewTimerinstance
- *@see#afterPropertiesSet()
- *@seejava.util.Timer#Timer(boolean)
- */
- protectedTimercreateTimer(booleandaemon){
- returnnewTimer(daemon);
- }
- publicObjectgetObject(){
- returnthis.timer;
- }
- publicClassgetObjectType(){
- returnTimer.class;
- }
- publicbooleanisSingleton(){
- returntrue;
- }
- /**
- *CanceltheTimeronbeanfactoryshutdown,stoppingallscheduledtasks.
- *@seejava.util.Timer#cancel()
- */
- publicvoiddestroy(){
- logger.info("CancellingTimer");
- this.timer.cancel();
- }
- }
這個類就是運行我們任務的類了,我們可以定製N個任務,只需要塞到這裏就ok了