1.首先注意:
Spring3.0不支持Quartz2.0
有个定时任务,想用之前的spring quartz定时执行,结果容器启动时报错:
Caused by: java.lang.IncompatibleClassChangeError: class org.springframework.scheduling.quartz.CronTriggerBean has interface org.quartz.CronTrigger as super class
2.xml文件(下面)
引入到Spring的applicationContext.xml文件里边
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd ">
<!-- 要调度的对象 -->
<bean id="jobDetail" class="org.springframework.scheduling.quartz.JobDetailBean">
<property name="jobClass">
<value>com.quartz.QuartzJob</value>
</property>
<property name="jobDataAsMap">
<map>
<!--service必须放到这里,才可以注入进去 -->
<description>jobDataAsMap</description>
<!-- key 属性值,value 对应的bean -->
<entry key="tempUserUidService" value-ref="tempUserUidService" />
</map>
</property>
</bean>
<!-- 定义触发的时间 -->
<bean id="cron" class="org.springframework.scheduling.quartz.CronTriggerBean">
<property name="jobDetail">
<ref bean="jobDetail"/>
</property>
<property name="cronExpression">
<value> 0 0/5 * * * ?</value> <!--每隔五分钟触发一次-->
</property>
</bean>
<!-- 定义触发器 -->
<bean class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
<property name="triggers">
<list>
<ref bean="cron"/>
</list>
</property>
</bean>
</beans>
3. jar包
quartz-1.8.5.jar以及Spring3.0.6的核心jar包
4.实现的对象
QuartzJob.java--------------------实现五分钟清楚一次表
package com.common.quartz;
import java.util.Date;
import java.util.GregorianCalendar;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.scheduling.quartz.QuartzJobBean;
import com.base.pojo.TempUserUidExample;
import com.base.pojo.TempUserUidExample.Criteria;
import com.base.service.TempUserUidService;
public class QuartzJob extends QuartzJobBean{
@Override
protected void executeInternal(JobExecutionContext context) throws JobExecutionException {
TempUserUidService tempUserUidService = (TempUserUidService)context.getJobDetail().getJobDataMap().get("tempUserUidService");
TempUserUidExample example = new TempUserUidExample();
Criteria c = example.createCriteria();
c.andStartTimeLessThanOrEqualTo(getTime5MinAgo());
tempUserUidService.deleteByExample(example);
}
public Date getTime5MinAgo(){
Date dateNow = new Date();
GregorianCalendar cal = new GregorianCalendar();
cal.setTime(dateNow);
cal.add(GregorianCalendar.MINUTE, -5);
Date date = cal.getTime();
return date;
}
}
5.
注意
******Spring的管理的service不能依靠注入,以及实现ApplicationContextAware获取context去获取,需要在xml文件里配置******