cron 定时任两种配置方式
第一种:xml文件方式
<bean id="commonTimer" class="com.course.wx.timer.CommonTimer"></bean><!--定时任务Bean --> <bean name="startQuartz" lazy-init="false" autowire="no" class="org.springframework.scheduling.quartz.SchedulerFactoryBean"> <property name="triggers"> <list> <ref bean="releaseQuestionTrigger" /> <ref bean="dealHistoryQuestionTrigger" /> </list> </property> </bean> <bean id="dealHistoryQuestionTrigger" class="org.springframework.scheduling.quartz.CronTriggerFactoryBean"> <property name="jobDetail"> <ref bean="dealHistoryQuestion" /> </property> <property name="cronExpression"> <value>0 23 15 * * ?</value> </property> </bean> <bean id="dealHistoryQuestion" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean"> <property name="targetObject"> <ref bean="commonTimer" /> </property> <property name="targetMethod"> <value>dealHistoryQuestion</value> </property> </bean>
第二种:注解方式
xml配置
<!-- Spring定时器注解开关--> <task:annotation-driven /> <!-- 此处对于定时时间的配置会被注解中的时间配置覆盖,因此,以注解配置为准 --> <task:scheduled-tasks scheduler="myScheduler"> <task:scheduled ref="scheduledTaskManager" method="autoCardCalculate" cron="* */5 * * * *"/> </task:scheduled-tasks> <task:scheduler id="myScheduler" pool-size="10"/>
Java代码
@Component("scheduledTaskManager") @Lazy(value=false) public class ScheduledTaskManager { public static final Integer RECOVER = 3; /** * cron表达式:* * * * * *(共6位,使用空格隔开,具体如下) * cron表达式:*(秒0-59) *(分钟0-59) *(小时0-23) *(日期1-31) *(月份1-12或是JAN-DEC) *(星期1-7或是SUN-SAT) */ @Autowired ProcedureService procedureService; /** * 定时卡点计算。每天凌晨 02:00 执行一次 * @throws AdqException */ @Scheduled(cron = "* */5 * * * *") public void autoCardCalculate() throws AdqException { List<WorkOrder> suspendItems = procedureService.querySuspendItems(); if (suspendItems != null && suspendItems.size() > 0) { for (WorkOrder order : suspendItems) { order.setStateId(RECOVER); order.setNotes("恢复执行"); procedureService.updateState(order); } } } }