1.实例
依赖
<dependency>
<groupId>commons-collections</groupId>
<artifactId>commons-collections</artifactId>
<version>3.2.1</version>
</dependency>
<dependency>
<groupId>org.opensymphony.quartz</groupId>
<artifactId>quartz-all</artifactId>
<version>1.6.1</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>3.1.1.RELEASE</version>
</dependency>
当然还需要spring的核心依赖
(1)具体执行任务的类
不用实现任何接口
public class MyJob
{
Logger logger = LoggerFactory.getLogger(MyJob.class);
public void execute() throws JobExecutionException {
logger.info("{} task is start", new Date());
}
}
(2)spring配置文件中定义执行任务的类,和需要执行的方法
<!-- 定义目标bean和bean中的方法 -->
<!-- =====================日常任务job========================== -->
<bean id="myJob" class="com.mycompany.quartz.MyJob">
</bean>
<bean id="myJobMethod" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
<property name="targetObject">
<ref bean="myJob"/>
</property>
<property name="targetMethod"> <!-- 要执行的方法名称 -->
<value>execute</value>
</property>
</bean>
(2)定义trigger
<!-- ======================== 调度触发器 ======================== -->
<bean id="myTriggerBean" class="org.springframework.scheduling.quartz.CronTriggerBean">
<property name="jobDetail" ref="myJobMethod"></property>
<property name="cronExpression" value="0/5 * * * * ?"></property>
</bean>
(3)定义调度工厂
<!-- ======================== 调度工厂 ======================== -->
<bean id="SpringJobSchedulerFactoryBean" class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
<property name="triggers">
<list>
<ref bean="myTriggerBean"/>
</list>
</property>
</bean>
2.注意
(1)spring的<beans>中一定不能定义default-autowire="byName"
(2) <beans>不能设置default-lazy-int="true",否则定时任务不会触发