一文教你实现Spring动态启停定时任务( 三 )

③将任务解析并添加到任务队列后 , 交由ScheduledTaskRegistrar类的scheduleTasks方法添加(注册)定时任务到环境中:
protected void scheduleTasks() {if (this.taskScheduler == null) {//获取ScheduledExecutorService对象 , 实际上都是使用ScheduledThreadPoolExecutor执行定时任务调度this.localExecutor = Executors.newSingleThreadScheduledExecutor();this.taskScheduler = new ConcurrentTaskScheduler(this.localExecutor);}if (this.triggerTasks != null) {for (TriggerTask task : this.triggerTasks) {addScheduledTask(scheduleTriggerTask(task));}}if (this.cronTasks != null) {for (CronTask task : this.cronTasks) {addScheduledTask(scheduleCronTask(task));}}if (this.fixedRateTasks != null) {for (IntervalTask task : this.fixedRateTasks) {addScheduledTask(scheduleFixedRateTask(task));}}if (this.fixedDelayTasks != null) {for (IntervalTask task : this.fixedDelayTasks) {addScheduledTask(scheduleFixedDelayTask(task));}}}private void addScheduledTask(@Nullable ScheduledTask task) {if (task != null) {this.scheduledTasks.add(task);}}由上述源码可以看出 , Spring原生定时任务的大概步骤如下: 1.扫描带@Scheduled注解的类和方法(
ScheduledAnnotationBeanPostProcessor.postProcessAfterInitialization(........)) 2.将定时任务解析完成后加入任务队列(ScheduledAnnotationBeanPostProcessor.processScheduled(........)) 3.将定时任务注册到当前运行环境 , 等待执行(ScheduledTaskRegistrar.scheduleTasks(.......)) 且@Scheduled的底层调度实现是ScheduledThreadPoolExecutor

作者:MrDong先生
链接:
https://juejin.cn/post/7111992569034178574
来源:稀土掘金




推荐阅读