@Scheduled定時器原理及@RefreshScope相互影響
1.ScheduledAnnotationBeanPostProcessor
@EnableScheduling
- @Import(SchedulingConfiguration.class)
- 注冊了ScheduledAnnotationBeanPostProcessor

@RestController
@RefreshScope //動態(tài)感知修改后的值
public class TestController implements ApplicationListener<RefreshScopeRefreshedEvent>{
@Value("${common.age}")
String age;
@Value("${common.name}")
String name;
@GetMapping("/common")
public String hello() {
return name+","+age;
}
//觸發(fā)@RefreshScope執(zhí)行邏輯會導(dǎo)致@Scheduled定時任務(wù)失效
@Scheduled(cron = "*/3 * * * * ?") //定時任務(wù)每隔3s執(zhí)行一次
public void execute() {
System.out.println("定時任務(wù)正常執(zhí)行。。。。。。");
}
@Override
public void onApplicationEvent(RefreshScopeRefreshedEvent event) {
this.execute();
}
}1.1 SmartInitializingSingleton#afterSingletonsInstantiated
ScheduledAnnotationBeanPostProcessor#afterSingletonsInstantiated
- DefaultListableBeanFactory#preInstantiateSingletons
- SmartInitializingSingleton#afterSingletonsInstantiated
- 沒干啥重要事情
1.2 RefreshScope處理ContextRefreshedEvent創(chuàng)建refresh中的bean
并調(diào)用ScheduledAnnotationBeanPostProcessor#postProcessAfterInitialization找出TestController中加了@Scheduled注解的方法。
ScheduledAnnotationBeanPostProcessor#postProcessAfterInitialization
- 發(fā)布ContextRefreshedEvent
- RefreshScope#onApplicationEvent
- Object bean = this.context.getBean(name); 獲取scope為refresh的bean:scopedTarget.testController
- 會調(diào)用至postProcessAfterInitialization
- 找到有@Scheduled注解的方法execute()
- tasks.add(this.registrar.scheduleCronTask(new CronTask(runnable, new CronTrigger(cron, timeZone))));
1.3 ScheduledAnnotationBeanPostProcessor本身也能處理ContextRefreshedEvent
這里真正開始調(diào)度1.2中找到的任務(wù)。
ScheduledAnnotationBeanPostProcessor#onApplicationEvent
- ScheduledAnnotationBeanPostProcessor也會處理ContextRefreshedEvent
- ScheduledAnnotationBeanPostProcessor#finishRegistration
- this.taskScheduler設(shè)置為ThreadPoolTaskScheduler(哪里配置的?)
- ScheduledTaskRegistrar#afterPropertiesSet
- ScheduledTaskRegistrar#scheduleTasks
- 開始執(zhí)行任務(wù),這cronTasks不為空,則執(zhí)行該任務(wù)
addScheduledTask(scheduleCronTask(task)); - ScheduledTaskRegistrar#scheduleCronTask
- scheduledTask.future = this.taskScheduler.schedule(task.getRunnable(), task.getTrigger());
- ThreadPoolTaskScheduler#schedule
- ReschedulingRunnable#schedule以及ReschedulingRunnable#run實現(xiàn)定時調(diào)度,線程池為ScheduledThreadPoolExecutor
2.@RefreshScope的影響
當(dāng)Nacos Config配置中心發(fā)布配置時,會調(diào)用RefreshScope#refreshAll。
此時會ScheduledAnnotationBeanPostProcessor#postProcessBeforeDestruction會將加了@RefreshScope的TestController里面的任務(wù)全部cancel掉。
public void refreshAll() {
super.destroy();
this.context.publishEvent(new RefreshScopeRefreshedEvent());
}
RefreshScope#refreshAll
- GenericScope.BeanLifecycleWrapper#destroy
- DisposableBeanAdapter#run
- ScheduledAnnotationBeanPostProcessor#postProcessBeforeDestruction會將TestController里面的任務(wù)全部cancel掉。
ScheduledAnnotationBeanPostProcessor#postProcessBeforeDestruction
@Override
public void postProcessBeforeDestruction(Object bean, String beanName) {
Set<ScheduledTask> tasks;
synchronized (this.scheduledTasks) {
tasks = this.scheduledTasks.remove(bean);
}
if (tasks != null) {
for (ScheduledTask task : tasks) {
task.cancel();
}
}
}
取消核心流程GenericScope#destroy()
public void destroy() {
List<Throwable> errors = new ArrayList<Throwable>();
Collection<BeanLifecycleWrapper> wrappers = this.cache.clear();
for (BeanLifecycleWrapper wrapper : wrappers) {
try {
Lock lock = this.locks.get(wrapper.getName()).writeLock();
lock.lock();
try {
wrapper.destroy();
}
finally {
lock.unlock();
}
}
catch (RuntimeException e) {
errors.add(e);
}
}
if (!errors.isEmpty()) {
throw wrapIfNecessary(errors.get(0));
}
this.errors.clear();
}2.1 ThreadPoolTaskScheduler在哪里配置的?
ThreadPoolTaskScheduler
- 構(gòu)造bean:nacosWatch:NacosWatch時會創(chuàng)建一個
- 構(gòu)造bean:taskScheduler:ThreadPoolTaskScheduler

public class TaskSchedulingAutoConfiguration {
@Bean
@ConditionalOnBean(name = TaskManagementConfigUtils.SCHEDULED_ANNOTATION_PROCESSOR_BEAN_NAME)
@ConditionalOnMissingBean({ SchedulingConfigurer.class, TaskScheduler.class, ScheduledExecutorService.class })
public ThreadPoolTaskScheduler taskScheduler(TaskSchedulerBuilder builder) {
return builder.build();
}
@Bean
@ConditionalOnMissingBean
public TaskSchedulerBuilder taskSchedulerBuilder(TaskSchedulingProperties properties,
ObjectProvider<TaskSchedulerCustomizer> taskSchedulerCustomizers) {
TaskSchedulerBuilder builder = new TaskSchedulerBuilder();
builder = builder.poolSize(properties.getPool().getSize());
Shutdown shutdown = properties.getShutdown();
builder = builder.awaitTermination(shutdown.isAwaitTermination());
builder = builder.awaitTerminationPeriod(shutdown.getAwaitTerminationPeriod());
builder = builder.threadNamePrefix(properties.getThreadNamePrefix());
builder = builder.customizers(taskSchedulerCustomizers);
return builder;
}2.2 TestController改造成ApplicationListener<RefreshScopeRefreshedEvent>
這樣做為什么能夠保證定時任務(wù)正常執(zhí)行?
- RefreshScope#refreshAll
- 發(fā)布RefreshScopeRefreshedEvent事件
- 調(diào)用到TestController代理對象#onApplicationEvent
- CglibAopProxy.DynamicAdvisedInterceptor#intercept
- SimpleBeanTargetSource#getTarget
- AbstractBeanFactory#getBean獲取scopedTarget.testController
- GenericScope#get
- 會創(chuàng)建真正的TestController實例,然后初始化后調(diào)用ScheduledAnnotationBeanPostProcessor#postProcessAfterInitialization找出TestController中加了@Scheduled注解的方法
- TestController#onApplicationEvent
- this.execute();
- 真正調(diào)用的是ReschedulingRunnable#run
以上就是@Scheduled定時器原理及@RefreshScope相互影響的詳細(xì)內(nèi)容,更多關(guān)于Scheduled定時器RefreshScope的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
SpringMVC 使用JSR-303進(jìn)行校驗 @Valid示例
本篇文章主要介紹了SpringMVC 使用JSR-303進(jìn)行校驗 @Valid示例,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-02-02
深入了解Java中循環(huán)結(jié)構(gòu)的使用
Java中有三種主要的循環(huán)結(jié)構(gòu):while 循環(huán)、do…while 循環(huán)和for 循環(huán)。本文將來和大家一起講講Java中這三個循環(huán)的使用,需要的可以參考一下2022-08-08
JAVA Spring中讓人頭痛的JAVA大事務(wù)問題要如何解決你知道嗎
這篇文章主要介紹了Java Spring事務(wù)使用及驗證過程詳解,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2021-09-09

