摘要:本文主要介绍基于SpringBoot定时任务ScheduledTaskRegistrar的动态扩展,实现定时任务的动态新增和删除。
ScheduledTaskRegistrar类简要描述
平常使用方式配置
Application启动类上添加注解@EnableScheduling
@EnableScheduling
@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class})
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
复制代码
- 在需要定时的方法上添加定时注解
@Scheduled(cron = "0/10 * * * * ?")
@Slf4j
@Component
public class OtherScheduler {
@Scheduled(cron = "0/10 * * * * ?")
public void print(){
log.info("每10S打印一次");
}
@Scheduled(cron = "0/5 * * * * ?")
public void print5(){
log.info("每5S打印一次");
}
}
复制代码
原理分析
默认的方式启动把
ScheduledAnnotationBeanPostProcessor该类实例化到SpringBoot的Bean管理中,并且该类持有一个ScheduledTaskRegistrar属性,然后扫描出来拥有@Scheduled注解的方法,添加到定时任务中。
- 添加定时任务到列表中
扫描到
@Scheduled注解的时候调用了该方法添加任务
public void addCronTask(Runnable task, String expression) {
if (!CRON_DISABLED.equals(expression)) {
addCronTask(new CronTask(task, expression));
}
}
复制代码
- 启动定时任务
在对象实例化

文章介绍了如何基于SpringBoot的ScheduledTaskRegistrar实现定时任务的动态新增和删除。通过扩展ScheduledTaskRegistrar,创建DynamicScheduledTaskRegistrar类,设置线程池大小,提供添加和删除任务的方法。示例展示了如何在服务中添加和取消定时任务,以及通过Controller接口进行操作。
最低0.47元/天 解锁文章
1万+

被折叠的 条评论
为什么被折叠?



