1.引入quartz.jar包;如果使用的maven引入方式:
<dependency>
<groupId>org.quartz-scheduler</groupId>
<artifactId>quartz</artifactId>
<version>1.8.5</version>
</dependency>
如果报错,可能是jar包冲突,可以将quartz.jar换成其他版本。
2.配置quartz
<bean id="mailTask" class="org.springframework.scheduling.quartz.JobDetailBean">
<property name="jobClass">
<value>cn.dayang.mis.question.common.QuestionTimerTask</value>
</property>
<property name="jobDataAsMap">
<map>
<entry key="questionBO">
<ref bean="questionBO"/>
</entry>
</map>
</property>
</bean>
<bean id="mailTaskTrigger" class="org.springframework.scheduling.quartz.CronTriggerBean">
<property name="jobDetail">
<ref bean="mailTask"/>
</property>
<property name="cronExpression">
<value>0 0 2 * * ?</value>
</property>
</bean>
<bean id="scheduler" class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
<property name="triggers">
<ref bean="mailTaskTrigger"/>
</property>
</bean>
3.编写执行类
public class QuestionTimerTask extends QuartzJobBean {
private QuestionBO questionBO;
protected void executeInternal(JobExecutionContext arg0)
throws JobExecutionException {
this.sendExceedEmail();
this.sendEveryDayEmail();
}
public void sendExceedEmail(){}
...
}
结果为每天凌晨两点执行QuestionTimerTask
2015-07-09:
spring4.1.7,quartz 2.1.3,sl4j1.7.12,log4j 1.2.17配置如下:
1.配置:<?xml version="1.0" encoding="gb2312"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">
<beans>
<bean id="pushTask" class="org.springframework.scheduling.quartz.JobDetailFactoryBean">
<property name="jobClass">
<value>weixin.timer.schedule.PushTimerTask</value>
</property>
<!--
<property name="jobDataAsMap">
<map>
<entry key="questionBO">
<ref bean="questionBO"/>
</entry>
</map>
</property>
-->
</bean>
<bean id="pushTaskTrigger" class="org.springframework.scheduling.quartz.CronTriggerFactoryBean">
<property name="jobDetail">
<ref bean="pushTask"/>
</property>
<property name="cronExpression">
<value>0 0/1 9-18 ? * MON-FRI</value>
</property>
</bean>
<bean id="scheduler" class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
<property name="triggers">
<ref bean="pushTaskTrigger"/>
</property>
</bean>
</beans>
2.定时程序实现类:
package weixin.timer.schedule;
import org.apache.log4j.Logger;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.scheduling.quartz.QuartzJobBean;
import weixin.busi.service.PushMessage;
import weixin.common.util.AesException;
import weixin.common.util.SingletonObject;
public class PushTimerTask extends QuartzJobBean{
private Logger log=Logger.getLogger(PushTimerTask.class);
@Override
protected void executeInternal(JobExecutionContext arg0)
throws JobExecutionException {
PushMessage pushMessage=SingletonObject.getPushMessageInstance();
try {
pushMessage.pushMessage();
} catch (AesException e) {
log.info("************由于aes解密失败导致消息推送失败************");
e.printStackTrace();
}
log.info("************消息推送方法调用完成************");
}
}
结果:每周周一至周五 9点至18点每隔一分钟执行定时推送程序