有两种流行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了
分享到:
相关推荐
spring定时器Spring定时器的两种实现方式Java的Timer类和OpenSymphony的Quartz。
本文向您介绍Spring定时器的两种实现方式,包括Java Timer定时和Quartz定时器,两种Spring定时器的实现方式各有优点,可结合具体项目考虑是否采用。
Spring两种定时器实例配置:Java的TimerTask类和OpenSymphony的Quartz。包含5种配置方式:timer普通定时器、timer特定方法定时器、quartz简单定时器、quartz精确定时器、quartz特定方法定时器。简单实用,一看就会。
并非应用系统中发生的所有事情都是由用户的动作引起的。...在Spring中有两种流行配置:Java的Timer类和OpenSymphony的Quartz来执行调度任务。下面以给商丘做的接口集抄900到中间库的日冻结数据传输为例:
Spring自带了一套定时任务工具Spring-Task,可以把它看成是一个轻量级的Quartz,使用起来十分简单,除Spring相关的包外不需要额外的包,支持注解和配置文件两种形式。通常情况下在Spring体系内,针对简单的定时任务...
在工作中有用到spring task作为定时任务的处理,spring通过接口TaskExecutor和TaskScheduler这两个接口的方式为异步定时任务提供了一种抽象。这就意味着spring容许你使用其他的定时任务框架,当然spring自身也提供了...
在我了解的过程中发现java实现定时任务有四种,首先是jdk自带的两个Timer,ScheduledThreadPoolExecutor,后者是jdk1.5提出的,因为这个Timer毛病着实有点多,像什么单线程,出问题了其他任务也执
//给客户发一个感谢消息,消息驱动Bean必须实现两个接口MessageDrivenBean和MessageListener 在对象创建的过程中将被容器调用,onMessage函数方法接收消息参数,将其强制转型为合适的消息类型,同时打印出消息...
//给客户发一个感谢消息,消息驱动Bean必须实现两个接口MessageDrivenBean和MessageListener 在对象创建的过程中将被容器调用,onMessage函数方法接收消息参数,将其强制转型为合适的消息类型,同时打印出消息...