springboot通过SchedulingConfigurer实现多定时任务注册及动态修改执行周期(示例详解)
作者:KeepSmiling_me
这篇文章主要介绍了springboot通过SchedulingConfigurer实现多定时任务注册及动态修改执行周期,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
springboot 通过SchedulingConfigurer实现多定时任务注册及动态修改执行周期
Spring 中定时任务有两种实现方式:
1.@Scheduled(cron表达式)
2.基于SchedulingConfigurer注册定时任务
这两者的区别主要有
1.@Scheduled不支持动态修改定时周期,只能停止服务器,修改cron表达式,再启动服务器;SchedulingConfigurer可以动态修改
2.@Scheduled只能是单线程,而SchedulingConfigurer默认是单线程,可以通过添加线程池,实现多线程下定时任务的运行
import org.springframework.scheduling.Trigger;
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;
import java.util.concurrent.Executors;
@Component
@EnableScheduling
public class Task implements SchedulingConfigurer {
@Override
public void configureTasks(ScheduledTaskRegistrar scheduledTaskRegistrar) {
//设置线程池
scheduledTaskRegistrar.setScheduler(Executors.newScheduledThreadPool(20));
//taskConfig中配置定时任务的相关信息
TaskConfig taskConfig = dutyConfigs.get(taskType);
//异步任务
Runnable runnable = () -> createByConfig(taskConfig);
Trigger trigger = triggerContext -> {
CronTrigger cronTrigger = new CronTrigger(taskConfig.getCron());
return cronTrigger.nextExecutionTime(triggerContext);
};
scheduledTaskRegistrar.addTriggerTask(runnable, trigger);
}
}到此这篇关于springboot通过SchedulingConfigurer实现多定时任务注册及动态修改执行周期的文章就介绍到这了,更多相关springboot多定时任务注册内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
