当前位置:网站首页>@Scheduled annotation pit, I stepped on it for you
@Scheduled annotation pit, I stepped on it for you
2022-06-29 23:36:00 【InfoQ】
The problem background
Spring@ScheduledSpring@Scheduled@Scheduled Failure cause analysis
@ScheduledSpringBoot@Scheduled@Scheduled
Spring@Scheduled
ScheduledAnnotationBeanPostProcessor@ScheduledBeanPostProcessorSpringbeanbeforeafterbeanSpringBeanPostProcessorpostProcessAfterInitializationbeanSpringBootScheduledAnnotationBeanPostProcessor
ScheduledAnnotationBeanPostProcessorpublic class ScheduledAnnotationBeanPostProcessor implements MergedBeanDefinitionPostProcessor, DestructionAwareBeanPostProcessor, Ordered, EmbeddedValueResolverAware, BeanNameAware, BeanFactoryAware, ApplicationContextAware, SmartInitializingSingleton, ApplicationListener<ContextRefreshedEvent>, DisposableBean {
...
public Object postProcessAfterInitialization(Object bean, String beanName) {
if (bean instanceof AopInfrastructureBean) {
return bean;
} else {
//(key-1) Parse all Scheduled Annotated classes
Class<?> targetClass = AopProxyUtils.ultimateTargetClass(bean);
if (!this.nonAnnotatedClasses.contains(targetClass)) {
Map<Method, Set<Scheduled>> annotatedMethods = MethodIntrospector.selectMethods(targetClass, new MetadataLookup<Set<Scheduled>>() {
public Set<Scheduled> inspect(Method method) {
Set<Scheduled> scheduledMethods = AnnotatedElementUtils.getMergedRepeatableAnnotations(method, Scheduled.class, Schedules.class);
return !scheduledMethods.isEmpty() ? scheduledMethods : null;
}
});
if (annotatedMethods.isEmpty()) {
this.nonAnnotatedClasses.add(targetClass);
if (this.logger.isTraceEnabled()) {
this.logger.trace("No @Scheduled annotations found on bean class: " + targetClass);
}
} else {
Iterator var5 = annotatedMethods.entrySet().iterator();
while(var5.hasNext()) {
Entry<Method, Set<Scheduled>> entry = (Entry)var5.next();
Method method = (Method)entry.getKey();
Iterator var8 = ((Set)entry.getValue()).iterator();
while(var8.hasNext()) {
Scheduled scheduled = (Scheduled)var8.next();
//(key-2) Handle classes modified by annotations
this.processScheduled(scheduled, method, bean);
}
}
if (this.logger.isDebugEnabled()) {
this.logger.debug(annotatedMethods.size() + " @Scheduled methods processed on bean '" + beanName + "': " + annotatedMethods);
}
}
}
return bean;
}
}
...
}
@Scheduled@Schedulesmapkey@Scheduled@Scheduleskey-1``mapprocessScheduledprotected void processScheduled(Scheduled scheduled, Method method, Object bean) {
try {
Runnable runnable = this.createRunnable(bean, method);
boolean processedSchedule = false;
String errorMessage = "Exactly one of the 'cron', 'fixedDelay(String)', or 'fixedRate(String)' attributes is required";
Set<ScheduledTask> tasks = new LinkedHashSet(4);
long initialDelay = scheduled.initialDelay();
...
//(key-1) Get the corresponding... In the annotation scron Parameters
String cron = scheduled.cron();
if (StringUtils.hasText(cron)) {
String zone = scheduled.zone();
if (this.embeddedValueResolver != null) {
cron = this.embeddedValueResolver.resolveStringValue(cron);
zone = this.embeddedValueResolver.resolveStringValue(zone);
}
if (StringUtils.hasLength(cron)) {
Assert.isTrue(initialDelay == -1L, "'initialDelay' not supported for cron triggers");
processedSchedule = true;
if (!"-".equals(cron)) {
TimeZone timeZone;
if (StringUtils.hasText(zone)) {
timeZone = StringUtils.parseTimeZoneString(zone);
} else {
timeZone = TimeZone.getDefault();
}
//(key-2) Add to task list
tasks.add(this.registrar.scheduleCronTask(new CronTask(runnable, new CronTrigger(cron, timeZone))));
}
}
}
...
Assert.isTrue(processedSchedule, errorMessage);
Map var18 = this.scheduledTasks;
synchronized(this.scheduledTasks) {
Set<ScheduledTask> regTasks = (Set)this.scheduledTasks.computeIfAbsent(bean, (key) -> {
return new LinkedHashSet(4);
});
regTasks.addAll(tasks);
}
} catch (IllegalArgumentException var25) {
throw new IllegalStateException("Encountered invalid @Scheduled method '" + method.getName() + "': " + var25.getMessage());
}
}
CronTask
springboot
public ScheduledTask scheduleCronTask(CronTask task) {
ScheduledTask scheduledTask = this.unresolvedTasks.remove(task);
boolean newTask = false;
if (scheduledTask == null) {
scheduledTask = new ScheduledTask();
newTask = true;
}
if (this.taskScheduler != null) {
scheduledTask.future = this.taskScheduler.schedule(task.getRunnable(), task.getTrigger());
}
else {
addCronTask(task);
this.unresolvedTasks.put(task, scheduledTask);
}
return (newTask ? scheduledTask : null);
}JVMJVMCPU ticksSpringSpring
public ScheduledFuture<?> schedule() {
synchronized (this.triggerContextMonitor) {
this.scheduledExecutionTime = this.trigger.nextExecutionTime(this.triggerContext);
if (this.scheduledExecutionTime == null) {
return null;
}
// Get time difference
long initialDelay = this.scheduledExecutionTime.getTime() - System.currentTimeMillis();
this.currentFuture = this.executor.schedule(this, initialDelay, TimeUnit.MILLISECONDS);
return this;
}
}
@ScheduledScheduledThreadPoolExecutorSystem.nanoTime边栏推荐
- [从零开始学习FPGA编程-51]:高阶篇 - 基于IP核的FPGA开发- 什么是FPGA IP核(软核、固核、硬核)与学习方法
- pytest初始化和清理环境
- Regular expressions: characters (2)
- Leetcode(76)——最小覆盖子串
- 动态代理的实现原理
- 海外数字身份验证服务商ADVANCE.AI入选EqualOcean《2022品牌出海服务市场研究报告》
- 手机开户一般哪个证券公司好?另外,手机开户安全么?
- Fund valuation, expenses and accounting
- PROJECT #1 - BUFFER POOL [CMU 15-445645]笔记
- Uniapp copy contents to clipboard
猜你喜欢

Node data collection and remote flooding transmission of label information

采购数智化爆发在即,支出宝“3+2“体系助力企业打造核心竞争优势

Intranet penetration (NC)

Speech signal processing (II): phonation physiology, auditory physiology and auditory psychology

NRM explanation

疫情下我离职一年,收入增长了10倍

Status acquisition and control system of on-site express cabinet

Software testing interface testing JMeter 5.5 installation tutorial

海外数字身份验证服务商ADVANCE.AI入选EqualOcean《2022品牌出海服务市场研究报告》

正则表达式:字符(2)
随机推荐
Discussion on distributed unique ID generation scheme
Shell -- text processing command
Uniapp copy contents to clipboard
[从零开始学习FPGA编程-51]:高阶篇 - 基于IP核的FPGA开发- 什么是FPGA IP核(软核、固核、硬核)与学习方法
Regular expressions: characters (2)
M1笔记本居家办公的痛点及解决方案 | 社区征文
Head pressing Amway good-looking and practical dispensing machine SolidWorks model material here
LC:有效的数独 + 旋转图像
Top ten securities companies: "bulldozer market" reappearance
“微博评论”的高性能高可用计算架构
手机开户一般哪个证券公司好?另外,手机开户安全么?
剑指 Offer 13. 机器人的运动范围
机器学习:VC维的概念和用途
字节云数据库未来方向的探索与实践
Solr basic operation 2
I hope you have no regrets about the regrettable things in the University
RRDTOOL draws MRTG log data
Effective self summary of remote communication | community essay solicitation
sql刷题595. 大的国家
记一次排查线上MySQL死锁过程,不能只会curd,还要知道加锁原理