spring-quartz定时任务调度

近日需交接同事的一些工作,其中包含定时任务这一块,早前了解过spring-quartz的整合,不过止于使用,今日刚好拿来复习一用,话不多说,开始进入正题;

使用到的相关jar包:

spring-asm-3.0.5.RELEASE.jar
spring-beans.jar
spring-context-support.jar
spring-context.jar
spring-core.jar
spring-expression.jar
spring-transaction-3.0.5.RELEASE .jar
spring-tx.jar
spring-web.jar
quartz-all-1.8.6.jar
commons-logging.jar
proxool-0.8.3.jar
slf4j-api-1.6.6.jar

 搜罗网上的资料,在spring中使用quartz有两种方式的实现:

继承 QuartzJobBean public class xx  extends QuartzJobBean{
       //QuartzJobBean为抽象类
      //实现它的executeInternal方法
}
xml配置文件中配置需要调用的类和类中的方法
<!--     要调用的工作类 -->
 <bean id="quartzJob" class="com.quartz.QuartzJob">
</bean>
 <bean id="jobtask" class="org.springframework.sche
duling.quartz.MethodInvokingJobDetailFactoryBean">
                    <!--             调用的类 -->
                    <property name="targetObject">
                          <ref bean="quartzJob"/>
                    </property>
                   <!--             调用类中的方法 -->
                   <property name="targetMethod">
                          <value>work</value>
                    </property>
</bean>

QuartzJobBean的代码:

package org.springframework.scheduling.quartz;
import java.lang.reflect.Method;
import java.util.Map;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.MutablePropertyValues;
import org.springframework.beans.PropertyAccessorFactory;
import org.springframework.util.ReflectionUtils;
public abstract class QuartzJobBean
  implements Job
{
  private static final Method getSchedulerMethod;
  private static final Method getMergedJobDataMapMethod;
  public final void execute(JobExecutionContext context)
    throws JobExecutionException
  {
    try
    {
      Scheduler scheduler = (Scheduler)ReflectionUtils.invokeMethod(getSchedulerMethod, context);
      Map mergedJobDataMap = (Map)ReflectionUtils.invokeMethod(getMergedJobDataMapMethod, context);
      BeanWrapper bw = PropertyAccessorFactory.forBeanPropertyAccess(this);
      MutablePropertyValues pvs = new MutablePropertyValues();
      pvs.addPropertyValues(scheduler.getContext());
      pvs.addPropertyValues(mergedJobDataMap);
      bw.setPropertyValues(pvs, true);
    }
    catch (SchedulerException ex) {
      throw new JobExecutionException(ex);
    }
    executeInternal(context);
  }
  protected abstract void executeInternal(JobExecutionContext paramJobExecutionContext)
    throws JobExecutionException;
  static
  {
    try
    {
      Class jobExecutionContextClass = QuartzJobBean.class.getClassLoader().loadClass("org.quartz.JobExecutionContext");
      getSchedulerMethod = jobExecutionContextClass.getMethod("getScheduler", new Class[0]);
      getMergedJobDataMapMethod = jobExecutionContextClass.getMethod("getMergedJobDataMap", new Class[0]);
    }
    catch (Exception ex) {
      throw new IllegalStateException("Incompatible Quartz API: " + ex);
    }
  }
}

=====================割一下=========================================================

好吧,直接贴代码:

第一种方式:----------------------------------------------> 继承QuartzJobBean

JAVA代码:

package com.quartz; 
import java.util.Date;
 import org.quartz.JobExecutionContext;
 import org.quartz.JobExecutionException; 
import org.springframework.scheduling.quartz.QuartzJobBean; 

public class QuartzJobForExtends extends QuartzJobBean{ 

private int timeout; 
private static int counter = 0;
 //注入,见XML配置 
public void setTimeout(int timeout) { this.timeout = timeout; } 

@Override 
protected void executeInternal(JobExecutionContext context)
throws JobExecutionException {
 System.out.println("继承QuartzJobBean" + ++counter + "进行中..."); 
 long ms = System.currentTimeMillis(); 
 System.out.println(new Date(ms)); 
 String s = (String) context.getMergedJobDataMap().get("service"); 
 System.out.println(this.timeout); 
 System.out.println(s); System.out.println(); } 
} 

对应xml内容:

<!--配置对应的class和初始化属性内容--> 
<bean id="myjob" class="org.springframework.scheduling.quartz.JobDetailBean">      
     <property name="jobClass" value="com.quartz.QuartzJobForExtends"></property>     
     <property name="jobDataAsMap">    
        <map>    
            <entry key="service"><value>xxxxxxxxx</value></entry>  
            <entry key="timeout" value="6" />    
        </map>    
     </property>    
    </bean> 

<!--配置任务调度时机   这里使用cron表达式--> 
<bean id="cronTrigger" class="org.springframework.scheduling.quartz.CronTriggerBean">  
    <property name="jobDetail" ref="myjob" />    
    <property name="cronExpression" value="0/10 * * * * ?" /><!--每10秒执行一次>  
   </bean>  
  
<bean   lazy-init="false" class="org.springframework.scheduling.quartz.SchedulerFactoryBean">  
    <property name="triggers">  
    <list>  
    <ref bean="cronTrigger" />  
    </list>  
    </property>  
</bean>  

PS:这里说一说任务调度的触发时机,主要也分为两种

触发机制 对应的调度器
具体实现
每隔指定时间则触发一次
org.springframework.scheduling.quartz.
SimpleTriggerBean

 <bean id="simpleTrigger" class="org.

springframework.scheduling.quartz.

SimpleTriggerBean">

 

 

 <property name="jobDetail" ref="my

job" />

<!--服务器启动多久后开始执行-->

<property name="startDelay" valu

e="0" />

 

<!-- 6秒刷新一次 , 单位:毫秒 -->

<property name="repeatInterv

al" value="6000" />

 

 

</bean>

每到指定时间则触发一次
org.springframework.scheduling.quartz.
CronTriggerBean
<bean id="cronTrigger" class="org
.springframework.scheduling.quar
tz.CronTriggerBean">
 
<property name="jobDetail" ref="
myjob" />  
<property name="cronExpressi
on" value="0/10 * * * * ?" />
    </bean>

个人偏爱cron表达,灵活,强大,fashion.....

第二种方式:----------------------------------------------> 

JAVA代码:

package com.quartz;

public class QuartzJob {
     public void work(){
    	 System.out.println("我在工作。。。。");
     }
}

 

XML配置:

         <!--要调用的工作类 -->
        <bean id="quartzJob" class="com.quartz.QuartzJob"></bean>
	    
         <!--定义调用对象和调用对象的方法 -->
        <bean id="jobtask" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
            <!--调用的类 -->
            <property name="targetObject">
                <ref bean="quartzJob"/>
            </property>
             <!--调用类中的方法 -->
            <property name="targetMethod">
                <value>work</value>
            </property>
        </bean>
        
        <!--定义触发时间 -->
        <bean id="doTime" class="org.springframework.scheduling.quartz.CronTriggerBean">
            <property name="jobDetail">
                <ref bean="jobtask"/>
            </property>
            <!--cron表达式 -->
            <property name="cronExpression">
                <value>0/10 * * * * ?</value>
            </property>
        </bean>
	
         <!--总管理类 如果将lazy-init='false'那么容器启动就会执行调度程序  -->
        <bean id="startQuertz" lazy-init="false" autowire="no" class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
            <property name="triggers">
                <list>
                    <ref bean="doTime"/>
                </list>
            </property>
        </bean>

 

Cron表达式就直接百度copy过来:

关于cronExpression表达式,这里讲解一下: 
字段 允许值 允许的特殊字符 
秒 0-59 , - * / 
分 0-59 , - * / 
小时 0-23 , - * / 
日期 1-31 , - * ? / L W C 
月份 1-12 或者 JAN-DEC , - * / 
星期 1-7 或者 SUN-SAT , - * ? / L C # 
年(可选) 留空, 1970-2099 , - * / 
表达式意义 
"0 0 12 * * ?" 每天中午12点触发 
"0 15 10 ? * *" 每天上午10:15触发 
"0 15 10 * * ?" 每天上午10:15触发 
"0 15 10 * * ? *" 每天上午10:15触发 
"0 15 10 * * ? 2005" 2005年的每天上午10:15触发 
"0 * 14 * * ?" 在每天下午2点到下午2:59期间的每1分钟触发 
"0 0/5 14 * * ?" 在每天下午2点到下午2:55期间的每5分钟触发 
"0 0/5 14,18 * * ?" 在每天下午2点到2:55期间和下午6点到6:55期间的每5分钟触发 
"0 0-5 14 * * ?" 在每天下午2点到下午2:05期间的每1分钟触发 
"0 10,44 14 ? 3 WED" 每年三月的星期三的下午2:10和2:44触发 
"0 15 10 ? * MON-FRI" 周一至周五的上午10:15触发 
"0 15 10 15 * ?" 每月15日上午10:15触发 
"0 15 10 L * ?" 每月最后一日的上午10:15触发 
"0 15 10 ? * 6L" 每月的最后一个星期五上午10:15触发 
"0 15 10 ? * 6L 2002-2005" 2002年至2005年的每月的最后一个星期五上午10:15触发 
"0 15 10 ? * 6#3" 每月的第三个星期五上午10:15触发 
每天早上6点 
0 6 * * * 
每两个小时 
0 */2 * * * 
晚上11点到早上8点之间每两个小时,早上八点 
0 23-7/2,8 * * * 
每个月的4号和每个礼拜的礼拜一到礼拜三的早上11点 
0 11 4 * 1-3 
1月1日早上4点 
0 4 1 1 * 

 

最后记得在web.xml中引入你的quartz定时任务的xml:

<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>
			classpath:quartz.xml
		</param-value>
	</context-param>

	<listener>
		<listener-class>
			org.springframework.web.context.ContextLoaderListener
		</listener-class>
	</listener>

 

最后需要注意的一点就是:

Spring3.1以下的版本必须使用quartz1的版本,spring3.1以及之后的版本才支持quartz2的版本

版本错误的话会报:

Caused by: org.springframework.beans.factory.CannotLoadBeanClassException: Error loading class [org.springframework.scheduling.quartz.CronTriggerBean] for bean with name 'mytrigger' defined in class path resource [applicationContext.xml]: problem with class file or dependent class; nested exception is java.lang.IncompatibleClassChangeError: class org.springframework.scheduling.quartz.CronTriggerBean has interface org.quartz.CronTrigger as super class

查看发现spring3.0.5中org.springframework.scheduling.quartz.CronTriggerBean继承了org.quartz.CronTrigger(public class CronTriggerBeanextends CronTrigger),而在quartz2.1.3中org.quartz.CronTrigger是个接口(publicabstract interface CronTrigger extends Trigger),而在quartz1.8.5及1.8.4中org.quartz.CronTrigger是个类(publicclass CronTrigger extends Trigger),从而造成无法在applicationContext中配置触发器。这是spring3.1以下版本和quartz2版本不兼容的一个bug。

此问题感谢博主[kevin19900306]的分享

 

以上作为quartz的简单事例,作为笔记,分享;

猜你喜欢

转载自msdghs.iteye.com/blog/2200315