透视Spring定时器相关功能

介绍一下Spring的定时器功能,它不仅实现起来方便,功能强大,而且在web开发时正好配合spring框架使用。

Spring支持jdk内置的Timer类和Quartz Scheduler

介绍spring的定时器,当然要先介绍配置文件applicationContext.xml了。

 
 
 
 
  1. <bean name="job" class="org.springframework.scheduling.quartz.JobDetailBean"> 
  2.  
  3.      <property name="jobClass"> 
  4.  
  5.          <value>jaoso.news.web.action.JobAction value> 
  6.  
  7.       property> 
  8.  
  9.      <property name="jobDataAsMap"> 
  10.  
  11.          <map> 
  12.  
  13.              <entry key="timeout"> 
  14.  
  15.                  <value>10 value> 
  16.  
  17.                entry> 
  18.  
  19.           map> 
  20.  
  21.       property> 
  22.  
  23. bean> 
  24.  

说明:org.springframework.scheduling.quartz.JobDetailBean是spring对你的类进行调度的代理,在jobClass中要指定你的任务类(com.yangsq.web.action.JobAction),在jobDataAsMap中向你的任务类中注入一些信息,当然也可以reference一个,不要忘记在你的任务里加入这些属性及set方法(有些罗嗦)。

timeout属性设定了当服务器启动后过10秒钟首次调用你的JobAction。

 
 
 
 
  1. <bean id="cronTrigger" class="org.springframework.scheduling.quartz.CronTriggerBean"> 
  2.  
  3.      <property name="jobDetail"> 
  4.  
  5.          <ref bean="job"/> 
  6.  
  7.       property> 
  8.  
  9.      <property name="cronExpression"> 
  10.  
  11.          <value>0 0/2 * * * ? value> 
  12.  
  13.       property> 
  14.  
  15. bean> 
  16.  

 

说明:org.springframework.scheduling.quartz.CronTriggerBean是spring提供的触发器,在这个触发器中设定了要触发的job(jobDetail属性设定了先前定义的bean),同时设定了触发时间(cronExpression)---每隔两分钟(0 0/2 * * * ?),这个的设定方式最后会说明。

 

         
         
         
         
  1. <bean class="org.springframework.scheduling.quartz.SchedulerFactoryBean"> 
  2.  
  3.      <property name="triggers"> 
  4.  
  5.          <list> 
  6.  
  7.              <ref local="cronTrigger"/> 
  8.  
  9.           list> 
  10.  
  11.       property> 
  12.  
  13. bean> 

 

说明:org.springframework.scheduling.quartz.SchedulerFactoryBean这是一个spring的工厂bean,在他的triggers属性列表中加入刚才定义的触发器,这里可以定义多个触发器(list嘛)。

 

好了,配置文件就介绍完了,该介绍com.yangsq.web.action.JobAction类了,

 

引入包:

 

              
              
              
              
  1. import org.quartz.JobExecutionContext;  
  2. import org.quartz.JobExecutionException;  
  3. import org.springframework.scheduling.quartz.QuartxJobBean; 

说明:QuartzJobBean是spring自带的,把spring的jar包加入就行了,但是前两个包要去下了,呵呵,google吧。

 

 

 

              
              
              
              
  1. public class JobAction extends QuartzJobBean{  
  2.  private int timeout;  
  3.  
  4. public void setTimeout(int timeout) {  
  5.     this.timeout = timeout;  

 

当然要继承QuartzJobBean了,但是光extends不行,必须要重载他的executeInternal方法

 

              
              
              
              
  1. protected void executeInternal (JobExecutionContext ctx)   
  2.  
  3. throws JobExecutionException{  
  4.     //加入你的任务  
  5. }  

 

好了,一个spring的时间调度完成了。

 

附:时间配置说明

 

sping定时器的时间配置十分强大,下面将介绍如何进行配置。

【编辑推荐】

  1. 用Spring framework实现定时器功能
  2. Spring定时器的两种实现方式

THE END