摘要:本文主要介绍基于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));
}
}
复制代码
- 启动定时任务