1、需要的jar包
spring-context-support-3.2.8.RELEASE.jar
commons-collections-3.2.1.jar (注 3.0以上即可,如果没有这个jar会报错:apache.../collections/SetUtils)
2、项目中加入applicationContext-quartz.xml内容如下
xmlns:batch="http://www.springframework.org/schema/batch"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/batch http://www.springframework.org/schema/batch/spring-batch-2.1.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">
---定义要执行的task
<bean id="helloWordJob" class="com.alibaba.bi21gov.condition.web.controller.HelloWorldTask">
<property name="valueType" value="i am chewenliang!"></property>
</bean>
----定义jobDetail,因为quartz.CronTriggerBean他要求的是一个jobDetail类型的对象,所以我们得通过MethodInvokingJobDetailFactoryBean来转一下
<bean id="helloWordJobDetail" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
<property name="targetObject">
<ref bean="helloWordJob" /> <!--目标Job-->
</property>
<property name="targetMethod">
<value>execute</value> <!--目标方法-->
</property>
<property name="concurrent">
<value>false</value> <!--设置是否同步-->
</property>
</bean>
---定义trigger的触发器--传入上面定义的jobDetail,定义时间策略
<!-- 触发器 -->
<bean id="helloWordJobCronTrigger" class="org.springframework.scheduling.quartz.CronTriggerBean" >
<property name="jobDetail" >
<ref bean="helloWordJobDetail" />
</property>
<property name="cronExpression" >
<value>0 0/1 * * * ?</value>
</property>
</bean>
<!-- 触发器工厂,将所有的定时任务都注入工厂-->
<bean class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
<!-- 添加触发器 -->
<property name="triggers">
<list>
<!-- 将上面定义的测试定时任务注入(可以定义多个定时任务,同时注入)-->
<ref local="helloWordJobCronTrigger" />
</list>
</property>
</bean>
3、task的定义,因为用的是传统的spring quart的用法 ,所以在定义task的时候不用继承或实现任何类,非常方便如下就行:
package com.alibaba.bi21gov.condition.web.controller;
public class HelloWorldTask{
---通过xml注入的参数
private String valueType;
public String getValueType() {
return valueType;
}
public void setValueType(String valueType) {
this.valueType = valueType;
}
--这个方法在xml要体现
public void execute(){
System.out.println(valueType);
}
}
4、测试
package com.alibaba.bi21gov.condition.web.controller;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class TestQuart {
public static void main(String[] args) {
BeanFactory factory = new ClassPathXmlApplicationContext("applicationContext-quartz.xml");
}
}
5、控制台打印:
i am chewenliang!
i am chewenliang!
i am chewenliang!
i am chewenliang!
i am chewenliang!
i am chewenliang!