Quartz总结(三):动态修改定时器一
package com.mc.bsframe.job; import org.quartz.Scheduler; import org.quartz.SchedulerException; import org.quartz.TriggerKey; import org.quartz.impl.triggers.SimpleTriggerImpl; import org.springframework.beans.factory.annotation.Autowired; import com.mc.bsframe.service.TestService; import com.mc.bsframe.util.TimeUtils; public class TestJob { @Autowired private TestService testSevice; public void doSomething() { testSevice.sayHi(); System.err.println("****:" + TimeUtils.getCurrentTime()); } private Scheduler scheduler; public Scheduler getScheduler() { return scheduler; } public void setScheduler(Scheduler scheduler) { this.scheduler = scheduler; } public void restJob(long time) { TriggerKey triggerKey=new TriggerKey("testTrigger", Scheduler.DEFAULT_GROUP); SimpleTriggerImpl simpleTrigger=null; try { simpleTrigger= (SimpleTriggerImpl) scheduler.getTrigger(triggerKey); } catch (SchedulerException e) { e.printStackTrace(); } simpleTrigger.setRepeatInterval(time); try { scheduler.rescheduleJob(triggerKey,simpleTrigger); } catch (SchedulerException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
代码如上:在任务类中注入Scheduler,然后添加restJob方法。
配置文件如下:
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" 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.xsd"> <!-- 要执行任务的任务类。 --> <bean id="testQuartz" class="com.mc.bsframe.job.TestJob"> <property name="scheduler" ref="schedulerFactoryBean"></property> </bean> <!-- 将需要执行的定时任务注入JOB中。 --> <bean id="testJob" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean"> <property name="targetObject" ref="testQuartz"></property> <!-- 任务类中需要执行的方法 --> <property name="targetMethod" value="doSomething"></property> <!-- 上一次未执行完成的,要等待有再执行。 --> <property name="concurrent" value="false"></property> </bean> <!-- 基本的定时器,会绑定具体的任务。 --> <bean id="testTrigger" class="org.springframework.scheduling.quartz.SimpleTriggerFactoryBean"> <property name="jobDetail" ref="testJob"></property> <property name="startDelay" value="3000"></property> <property name="repeatInterval" value="2000"></property> </bean> <bean id="schedulerFactoryBean" class="org.springframework.scheduling.quartz.SchedulerFactoryBean"> <property name="triggers"> <list> <ref bean="testTrigger"></ref> </list> </property> </bean> </beans>
使用方法:
@Autowired @Qualifier(value="testQuartz") private TestJob job; @RequestMapping("/job") public void job(Long time){ job.restJob(time); }
Doing is better than nothing