理解Spring的定制任务

相信做软件的朋友都有这样的经历,我的软件是不是少了点什么东西呢?比如定时任务啊!就拿新闻发布系统来说,如果新闻的数据更新太快,势必涉及一个问题,这些新闻不能由人工的去发布,应该让系统自己发布,这就需要用到定时定制任务了,以前定制任务无非就是设计一个Thread,并且设置运行时间片,让它到了那个时间执行一次,就ok了,让系统启动的时候启动它,想来也够简单的。不过有了spring,我想这事情就更简单了。

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

XML代码:

< bean   id = "infoCenterAutoBuildTask"   
class = "com.teesoo.teanet.scheduling.InfoCenterAutoBuildTask" >   
< property   name = "baseService"   ref = "baseService"   />   
< property   name = "htmlCreator"   ref = "htmlCreator"   />   
   

< bean   id = "scheduledTask"   
class = "org.springframework.scheduling.timer.ScheduledTimerTask" >   
   
< property   name = "delay"   value = "10000"   />   
   
< property   name = "period"   value = "1000000"   />   
< property   name = "timerTask"   ref = "infoCenterAutoBuildTask"   /> 
      

< bean   id = "timerFactory"  

class = "org.springframework.scheduling.timer.TimerFactoryBean" >   
< property   name = "scheduledTimerTasks" >   
< list >   
   
< ref   bean = "scheduledTask"   />   
   
   

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

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

Java代码:

BaseTask  extends  java.util.TimerTask {   
//用户只需要实现这个方面,把自己的任务放到这里   
public   void  run(){   
}   
}

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

Java代码:

/*  
* Copyright 2002-2005 the original author or authors.  
*   
* Licensed under the Apache License, Version 2.0 (the "License");  
* you may not use this file except in compliance with the License.  
* You may obtain a copy of the License at  
*   
*      http://www.apache.org/licenses/LICENSE-2.0  
*   
* Unless required by applicable law or agreed to in writing, software  
* distributed under the License is distributed on an "AS IS" BASIS,  
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  
* See the License for the specific language governing permissions and  
* limitations under the License.  
*/   

package  org.springframework.scheduling.timer;   

import  java.util.TimerTask;   

/**  
* JavaBean that describes a scheduled TimerTask, consisting of  
* the TimerTask itself (or a Runnable to create a TimerTask for)  
* and a delay plus period. Period needs to be specified;  
* there is no point in a default for it.  
*  
*

The JDK Timer does not offer more sophisticated scheduling

* options such as  cron expressions. Consider using Quartz for  
* such advanced needs.  
*  
*


Note that Timer uses a TimerTask instance that is shared

* between repeated executions, in contrast to Quartz which  
* instantiates a new Job for each execution.  
*  
* @author Juergen Hoeller  
* @since 19.02.2004  
* @see java.util.TimerTask  
* @see java.util.Timer#schedule(TimerTask, long, long)  
* @see java.util.Timer#scheduleAtFixedRate(TimerTask, long, long)  
*/   
public   class  ScheduledTimerTask {   

private  TimerTask timerTask;   

private   long  delay =  0 ;   

private   long  period =  0 ;   

private   boolean  fixedRate =  false ;     

/**  
* Create a new ScheduledTimerTask,  
* to be populated via bean properties.  
* @see #setTimerTask  
* @see #setDelay  
* @see #setPeriod  
* @see #setFixedRate  
*/   
public  ScheduledTimerTask() {   
}   

/**  
* Create a new ScheduledTimerTask, with default  
* one-time execution without delay.  
* @param timerTask the TimerTask to schedule  
*/   
public  ScheduledTimerTask(TimerTask timerTask) {   
this .timerTask = timerTask;   
}   

/**  
* Create a new ScheduledTimerTask, with default  
* one-time execution with the given delay.  
* @param timerTask the TimerTask to schedule  
* @param delay the delay before starting the task for the first time (ms)  
*/   
public  ScheduledTimerTask(TimerTask timerTask,  long  delay) {   
this .timerTask = timerTask;   
this .delay = delay;   
}   

/**  
* Create a new ScheduledTimerTask.  
* @param timerTask the TimerTask to schedule  
* @param delay the delay before starting the task for the first time (ms)  
* @param period the period between repeated task executions (ms)  
* @param fixedRate whether to schedule as fixed-rate execution  
*/   
public  ScheduledTimerTask(TimerTask timerTask,  long  delay,  long  period, 

boolean  fixedRate) {   
this .timerTask = timerTask;   
this .delay = delay;   
this .period = period;   
this .fixedRate = fixedRate;   
}   

/**  
* Create a new ScheduledTimerTask, with default  
* one-time execution without delay.  
* @param timerTask the Runnable to schedule as TimerTask  
*/   
public  ScheduledTimerTask(Runnable timerTask) {   
setRunnable(timerTask);   
}   

/**  
* Create a new ScheduledTimerTask, with default  
* one-time execution with the given delay.  
* @param timerTask the Runnable to schedule as TimerTask  
* @param delay the delay before starting the task for the first time (ms)  
*/   
public  ScheduledTimerTask(Runnable timerTask,  long  delay) {   
setRunnable(timerTask);   
this .delay = delay;   
}   

/**  
* Create a new ScheduledTimerTask.  
* @param timerTask the Runnable to schedule as TimerTask  
* @param delay the delay before starting the task for the first time (ms)  
* @param period the period between repeated task executions (ms)  
* @param fixedRate whether to schedule as fixed-rate execution  
*/   
public  ScheduledTimerTask(Runnable timerTask,  long  delay,  long  period, 

boolean  fixedRate) {   
setRunnable(timerTask);   
this .delay = delay;   
this .period = period;   
this .fixedRate = fixedRate;   
}      

/**  
* Set the Runnable to schedule as TimerTask.  
* @see DelegatingTimerTask  
*/   
public   void  setRunnable(Runnable timerTask) {   
this .timerTask =  new  DelegatingTimerTask(timerTask);   
}   

/**  
* Set the TimerTask to schedule.  
*/   
public   void  setTimerTask(TimerTask timerTask) {   
this .timerTask = timerTask;   
}   

/**  
* Return the TimerTask to schedule.  
*/   
public  TimerTask getTimerTask() {   
return  timerTask;   
}   

/**  
* Set the delay before starting the task for the first time,  
* in milliseconds. Default is 0, immediately starting the  
* task after successful scheduling.  
*/   
public   void  setDelay( long  delay) {   
this .delay = delay;   
}   

/**  
* Return the delay before starting the job for the first time.  
*/   
public   long  getDelay() {   
return  delay;   
}   

/**  
* Set the period between repeated task executions, in milliseconds.  
* Default is 0, leading to one-time execution. In case of a positive  
* value, the task will be executed repeatedly, with the given interval  
* inbetween executions.  
*

 

Default is "false": The timer will automatically get cancelled on

* destruction of this FactoryBean. Hence, if the application shuts down,  
* tasks will by default finish their execution. Specify "true" for eager  
* shutdown of threads that execute tasks.  
* @see java.util.Timer#Timer(boolean)  
*/   
public   void  setDaemon( boolean  daemon) {   
this .daemon = daemon;   
}     

public   void  afterPropertiesSet() {   
logger.info( "Initializing Timer" );   
this .timer = createTimer( this .daemon);   

// Register all ScheduledTimerTasks.   
if  ( this .scheduledTimerTasks !=  null ) {   
for  ( int  i =  0 ; i <  this .scheduledTimerTasks.length; i++) {   
ScheduledTimerTask scheduledTask =  this .scheduledTimerTasks[i];   
if  (scheduledTask.getPeriod() >  0 ) {   
// repeated task execution   
if  (scheduledTask.isFixedRate()) {   
this .timer.scheduleAtFixedRate(   
scheduledTask.getTimerTask(), scheduledTask.getDelay(),

scheduledTask.getPeriod());   
}   
else  {   
this .timer.schedule(   
scheduledTask.getTimerTask(), scheduledTask.getDelay(),

scheduledTask.getPeriod());   
}   
}   
else  {   
// One-time task execution.   
this .timer.schedule(scheduledTask.getTimerTask(),

scheduledTask.getDelay());   
}   
}   
}   
}   

/**  
* Create a new Timer instance. Called by afterPropertiesSet.  
* Can be overridden in subclasses to provide custom Timer subclasses.  
* @param daemon whether to create a Timer that runs as daemon thread  
* @return a new Timer instance  
* @see #afterPropertiesSet()  
* @see java.util.Timer#Timer(boolean)  
*/   
protected  Timer createTimer( boolean  daemon) {   
return   new  Timer(daemon);   
}      

public  Object getObject() {   
return   this .timer;   
}   

public  Class getObjectType() {   
return  Timer. class ;   
}   

public   boolean  isSingleton() {   
return   true ;   
}      

/**  
* Cancel the Timer on bean factory shutdown, stopping all scheduled tasks.  
* @see java.util.Timer#cancel()  
*/   
public   void  destroy() {   
logger.info( "Cancelling Timer" );   
this .timer.cancel();   
}      
}

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值