自触发定时任务,主要在spring容器里面配置组件,调度工厂、触发器、任务等等,下面以web应用常见的日志清理为例
1、设置触发任务
<!-- 日志清理任务 --> <bean id="scheduledDelLogTask" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean"> <property name="targetObject" ref="delLogTask"></property> <property name="targetMethod" value="delLog"></property> <property name="concurrent" value="false"></property> </bean>2、设置触发器
<!-- 日志清理,每月1日零点启动 --> <bean id="deleteLogTaskTrigger" class="org.springframework.scheduling.quartz.CronTriggerBean"> <property name="jobDetail" ref="scheduledDelLogTask" /> <property name="cronExpression" value="0 0 0 1 * ?"/> </bean>
3、设置调度工厂
<!-- 任务调度 --> <bean id="schedulerFactory" class= "org.springframework.scheduling.quartz.SchedulerFactoryBean"> <property name="triggers"> <list> <ref bean="deleteLogTaskTrigger"/> </list> </property> </bean>
触发任务的targetObject,对应后台执行代码类,Method对应执行方法
@Component("delLogTask") public class DelLogTask { public void delLog(){ log.info("开始清理操作日志定时任务!-"); } }