Thisarticleisoriginal(pleaseindicatethesourceforreprint):Howtorealizedynamicregistrationorcancellationof@Scheduledcrontimingtasks?-Jianshu(jianshu.com)IntherealbusinessscenarioofSpring,@Scheduledcanspecifycronexpressionsbyreadingconfigurationorhardcodingtorealizethefunctionoftriggeringatimedtaskatacertaintime,butweneednotrestarttheservice.Todynamicallymodifythetriggertimeofscheduledtasks,theoriginalfunctioncannotberealized.@Scheduled原理@EnableScheduling注解引入SchedulingConfiguration配置类SchedulingConfiguration注册ScheduledAnnotationBeanPostProcessorScheduled注解后处理器实例ScheduledAnnotationBeanPostProcessor#postProcessAfterInitializationScheduled注解后处理器扫描带org.springframework.scheduling.annotation.ScheduledAnnotationBeanPostProcessor#postProcessAfterInitialization@Scheduled的方法根据注解中定义的属性,BuildandregistertimedtaskimplementationideasFindthepartregisteredbytheprocessoraftertheScheduledannotation,andcheckthesourcecodea.Whethertoreserveanextensiblepart(forexample,somelogicalforwarding,forwardingtootherinterfaceinstancesorotherabstractmethods)b.Whetheritcanbeinheritedc.Whetherthekeymethodisprotectedornotd.Usereflection(thenextstep)tofindtheextensionmethodandencapsulatetheregistration/logoutlogictoimplementtheidea.ThetimingtaskregistrationlogicisintheScheduledAnnotationBeanPostProcessor#processScheduledmethod,themethodisprotected,createasubclass,andyoucanaccessthismethod.该方法需要传入Scheduled注解实例,创建代理,构建注解对象实例a。找到现有的框架逻辑i。找到注解ii开头的Utils方法和Factory方法。Jdk有一个创建注解实例的方法`sun.reflect.annotation.AnnotationParser#annotationForMap`iii。Hibernate有一个类似的方法`AnnotationDescriptor.Builder`可以构建`org.hibernate.validator.internal.util.annotation.AnnotationFactory#create`iv。Spring框架有一个类似的方法`org.springframework.core.annotation.AnnotationUtils#synthesizeAnnotation(java.util.Map,java.lang.Class,java.lang.reflect.AnnotatedElement)`b。复制框架逻辑(下层策略)c.自己创建一个代理实例(下一步)计划任务注销类似的逻辑在ScheduledAnnotationBeanPostProcessor#postProcessBeforeDestructiona.scheduledTasks的私有属性无法访问,只能使用反射具体代码逻辑;导入org.springframework.scheduling.annotation.Scheduled;导入org.springframework.scheduling.annotation.ScheduledAnnotationBeanPostProcessor;导入或g.springframework.scheduling.config.CronTask;importorg.springframework.scheduling.config.ScheduledTask;importorg.springframework.stereotype.Component;importjava.lang.reflect.Method;importjava.util.Map;importjava.util.Set;importstaticjava.util.Collections.emptySet;/***@authoruhfun*/@ComponentpublicclassConfigurableScheduler{privatefinalInnerScheduledAnnotationBeanPostProcessorpostProcessor;publicConfigurableScheduler(InnerScheduledAnnotationBeanPostProcessorpostProcessor){this.postProcessor=postProcessor;}publicvoidregisterCronTask(Stringcron,Methodmethod,Objecttarget){postProcessor.registerCronTask(cron,method,target);}publicvoidunregisterCronTask(Stringcron,Objecttarget){postProcessor.unregisterCronTask(target,cron);}@ComponentpublicstaticclassInnerScheduledAnnotationBeanPostProcessorextendsScheduledAnnotationBeanPostProcessor{privatefinalMap