SpringBoot—动态修改定时任务cron参数

时间:2022-06-20 07:52:25

动态修改定时任务cron参数
不需要重启应用就可以动态的改变Cron表达式的值
不能使用@Scheduled(cron = “${jobs.cron}”)实现

代码如下:

@Service
public class ScheduledForDynamicCron implements SchedulingConfigurer {

private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");

private static final String DEFAULT_CRON = "0/5 * * * * ?";
private String cron = DEFAULT_CRON;

@Override
public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
taskRegistrar.addTriggerTask(() -> {
// 定时任务的业务逻辑
System.out.println("动态修改定时任务cron参数,当前时间:" + dateFormat.format(new Date()));
}, (triggerContext) -> {
// 定时任务触发,可修改定时任务的执行周期
CronTrigger trigger = new CronTrigger(cron);
Date nextExecDate = trigger.nextExecutionTime(triggerContext);
return nextExecDate;
});
}

public void setCron(String cron) {
System.out.println("当前cron="+this.cron+"->将被改变为:"+cron);
this.cron = cron;
}

}
@RestController
@RequestMapping("/dynamic-scheduled")
public class DynamicScheduledController {


@Autowired
ScheduledForDynamicCron scheduledForDynamicCron;

@RequestMapping(value = "/update-cron")
public String updateDynamicScheduledTask(@RequestParam("cron") String cron) {

scheduledForDynamicCron.setCron(cron);

return "success";
}
@SpringBootApplication
@EnableScheduling
@ComponentScan(basePackageClasses = MytestApplication.class,
excludeFilters = @ComponentScan.Filter(SpringBootApplication.class))
public class MytestApplication {

public static void main(String[] args){
SpringApplication.run(MytestApplication.class, args);
}
}

运行结果:

动态修改定时任务cron参数,当前时间:20:34:40
动态修改定时任务cron参数,当前时间:20:34:45
动态修改定时任务cron参数,当前时间:20:34:50
动态修改定时任务cron参数,当前时间:20:34:55
2017-05-14 20:34:57.855 INFO 9939 --- [nio-8080-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring FrameworkServlet 'dispatcherServlet'
2017-05-14 20:34:57.855 INFO 9939 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : FrameworkServlet 'dispatcherServlet': initialization started
2017-05-14 20:34:57.866 INFO 9939 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : FrameworkServlet 'dispatcherServlet': initialization completed in 11 ms
当前cron=0/5 * * * * ?->将被改变为:0/10 * * * * ?
动态修改定时任务cron参数,当前时间:20:35:00
动态修改定时任务cron参数,当前时间:20:35:10
动态修改定时任务cron参数,当前时间:20:35:20
动态修改定时任务cron参数,当前时间:20:35:30
动态修改定时任务cron参数,当前时间:20:35:40
动态修改定时任务cron参数,当前时间:20:35:50