1,quartz-all-1.7.3.jar
2,web.xml
<context-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/spring/applicationContext*.xml</param-value> </context-param>
3,applicationContext.xml配置调度器
<!-- 调度器 --> <bean name="scheduler" class="org.springframework.scheduling.quartz.SchedulerFactoryBean"> <property name="startupDelay" value="10"></property> <property name="quartzProperties"> <props> <prop key="org.quartz.scheduler.skipUpdateCheck">true</prop> <prop key="org.terracotta.quartz.skipUpdateCheck">true</prop> </props> </property> <property name="triggers"> <list> <!-- 触发器列表--> <ref bean="ContractIncomeDateGeneratorTaskTrigger"/> </list> </property> </bean>
4,applicationContext-contractincome.xml
<?xml version="1.0" encoding="utf-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd"> <bean id="ContractIncomeDateGenerator" class="com.xxx.services.task.contractincome.ContractIncomeDateGenerator" scope="singleton"></bean> <bean id="ContractIncomeDateGeneratorTask" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean"> <property name="targetObject"> <ref bean="ContractIncomeDateGenerator" /> </property> <property name="targetMethod"> <value>doGenerate</value> </property> </bean> <bean id="ContractIncomeDateGeneratorTaskTrigger" class="org.springframework.scheduling.quartz.CronTriggerBean"> <property name="description" value="收入定时任务"></property> <property name="jobDetail" ref="ContractIncomeDateGeneratorTask" /> <property name="cronExpression" value="0 0 18 ? * *" /><!-- 每天18点执行一次 --> </bean> </beans>
5,java类 ContractIncomeDateGenerator.java
public class ContractIncomeDateGenerator {
private Logger logger = Logger.getLogger(ContractIncomeDateGenerator.class);
@Autowired
private ContractIncomeDao contractIncomeDao;
@Resource(name="TaskMailSender")
private TaskMailSender mailSender;
public void doGenerate() throws Exception {
try{
//执行相关操作
}
catch (Exception e) {
logger.error("定时任务错误!", e);
}
}
}
备注:设置执行时间参考 Quartz在Spring中动态设置cronExpression