当前位置:网站首页>@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边栏推荐
猜你喜欢

Paper writing tool: latex online website

matplotlib matplotlib中plt.hist()参数解释

Head on Amway! Good looking and practical motor SolidWorks model material see here

matlab习题 —— 程序控制流程练习

新钛云服荣膺“2022爱分析 · IT运维厂商全景报告”云管理平台CMP 代表厂商!...

Yunhe enmo Guoqiang, identifiez - le, saisissez - le, avant l'ébullition de la base de données nationale

matplotlib matplotlib可视化之柱状图plt.bar()

Redis client

开始“收割”!钉钉调整“钉钉Teambition”免费用人数上限,超十人将无法正常用

穿越过后,她说多元宇宙真的存在
随机推荐
Pain points and solutions of M1 notebook home office | community essay solicitation
Regular expressions: characters (2)
穿越过后,她说多元宇宙真的存在
Become the only key
绿树公司官方网站
NRM explanation
matlab习题 —— 程序控制流程练习
基于OpenStack的虚拟机在线迁移
字节云数据库未来方向的探索与实践
论文阅读《Large-Scale Direct SLAM with Stereo Cameras》
为什么 JSX 语法这么香?
How can the local / park do a good job in industrial analysis?
新钛云服荣膺“2022爱分析 · IT运维厂商全景报告”云管理平台CMP 代表厂商!...
C指针进阶2-->函数指针数组 回调函数简化计算器代码,基于回调函数模拟实现qsort函数
大学里遗憾的事,希望你无怨也无悔
Pytest initializing and cleaning up the environment
开始“收割”!钉钉调整“钉钉Teambition”免费用人数上限,超十人将无法正常用
Solr基础操作
Some of my favorite websites
AI赋能新零售,「智」胜之道在于生态思维|数智夜话直播精选摘录