Spring @Scheduled定时任务动态修改cron参数

时间:2022-06-20 07:52:31
  1. 在定时任务类上增加@EnableScheduling注解,并实现SchedulingConfigurer接口。(注意低版本无效)
  2. 设置一个静态变量cron,用于存放任务执行周期参数。
  3. 另辟一线程,用于模拟实际业务中外部原因修改了任务执行周期。
  4. 设置任务触发器,触发任务执行,其中就可以修改任务的执行周期。

Class : SpringDynamicCornTask

package com.xindatai.ibs.lime.dycSchedul;

import java.util.Date;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Lazy;
import org.springframework.scheduling.Trigger;
import org.springframework.scheduling.TriggerContext;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.stereotype.Component;

/**
* Spring动态周期定时任务 在不停应用的情况下更改任务执行周期
*
*
@author Liang
*
* 2017年6月1日
*/
@Lazy(
false)
@Component
@EnableScheduling
public class SpringDynamicCornTask implements SchedulingConfigurer {

private static final Logger logger = LoggerFactory.getLogger(SpringDynamicCornTask.class);

private static String cron;

private SpringDynamicCornTask() {
cron
= "0/5 * * * * ?";
// 开启新线程模拟外部更改了任务执行周期
new Thread(new Runnable() {

@Override
public void run() {
try {
Thread.sleep(
15 * 1000);
}
catch (InterruptedException e) {
e.printStackTrace();
}
cron
= "0/10 * * * * ?";
System.out.println(
"cron change to : " + cron);
}
}).start();
}

@Override
public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
taskRegistrar.addTriggerTask(
new Runnable() {

@Override
public void run() {
// 任务逻辑
logger.info("dynamicCronTask is running...");
}
},
new Trigger() {

@Override
public Date nextExecutionTime(TriggerContext triggerContext) {
// 任务触发,可修改任务的执行周期
CronTrigger trigger = new CronTrigger(cron);
Date nextExecutionTime
= trigger.nextExecutionTime(triggerContext);
return nextExecutionTime;
}
});
}
}

Console : 

[INFO  2017-06-01 12:26:25 SpringDynamicCornTask] - dynamicCronTask is running...
[INFO
2017-06-01 12:26:30 SpringDynamicCornTask] - dynamicCronTask is running...
[INFO
2017-06-01 12:26:35 SpringDynamicCornTask] - dynamicCronTask is running...
cron change to :
0/10 * * * * ?
[INFO
2017-06-01 12:26:40 SpringDynamicCornTask] - dynamicCronTask is running...
[INFO
2017-06-01 12:26:50 SpringDynamicCornTask] - dynamicCronTask is running...
[INFO
2017-06-01 12:27:00 SpringDynamicCornTask] - dynamicCronTask is running...

啦啦啦

 

啦啦啦