有两种流行Spring定时器配置:Java的Timer类和OpenSymphony的Quartz。
1.Java Timer定时
相信做软件的朋友都有这样的经历,我的软件是不是少了点什么东西呢?比如定时任务啊,
就拿新闻发布系统来说,如果新闻的数据更新太快,势必涉及一个问题,这些新闻不能由人工的去发布,应该让系统自己发布,这就需要用到定时定制任务了,以前定制任务无非就是设计一个Thread,并且设置运行时间片,让它到了那个时间执行一次,就ok了,让系统启动的时候启动它,想来也够简单的。不过有了spring,我想这事情就更简单了。
看看spring的配置文件,想来就只有这个配置文件了
xml 代码
- <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;
java 代码
- BaseTaskextendsjava.util.TimerTask{
- //用户只需要实现这个方面,把自己的任务放到这里
- publicvoidrun(){
- }
- }
下面让我们来看看 spring的源代码
java 代码
- /*
- *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,里面也就只有几个属性,一个是时间片,一个是任务等。
真正运行我们的任务的类是:
java 代码
- /*
- *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了