springboot 定时任务之Scheduled £神魔★判官ぃ 2022-10-27 01:36 199阅读 0赞 springboot 定时任务Scheduled方案是常用的方案: 一、代码设计 1、启动类设置: import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.scheduling.annotation.EnableScheduling; @SpringBootApplication //定时任务 的注解,必须加上 @EnableScheduling public class SpringbootApplication { public static void main(String[] args) { SpringApplication.run(SpringbootApplication.class, args); } } 2、骨骼代码如下: @Component//必须加上次注解,以便spring启动时扫描到 public class MailTask { private static Logger logger = LoggerFactory.getLogger(MailTask.class); @Autowired private CommonService commonService; @Autowired private SysSchedulerMapper sysSchedulerMapper; @SuppressWarnings("unchecked") // @Scheduled(cron="0 0 2 * * ?") //定时任务的参数设置,每天早上2点 @Scheduled(cron="0/600 * * * * ? ") //每600秒执行一次 public void handleTask(){ //业务代码省略........... } 二、参数源码详解 1、@EnableScheduling 注解原理:点开注解进入 @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) @Import(SchedulingConfiguration.class)//引入此类,为入口 @Documented public @interface EnableScheduling { } 2、点击 SchedulingConfiguration.class 进入: @Configuration @Role(BeanDefinition.ROLE_INFRASTRUCTURE) public class SchedulingConfiguration { //定义ScheduledAnnotationBeanPostProcessor这个bean。就会在context初始化时候,查找我们代码中的@Scheduled注解,并把它们转换为定时任务 @Bean(name = TaskManagementConfigUtils.SCHEDULED_ANNOTATION_PROCESSOR_BEAN_NAME) @Role(BeanDefinition.ROLE_INFRASTRUCTURE) public ScheduledAnnotationBeanPostProcessor scheduledAnnotationProcessor() { return new ScheduledAnnotationBeanPostProcessor();//初始化此类 } } 3、点击ScheduledAnnotationBeanPostProcessor 核心类进行源码分析进入: //spring的容器有多个,有的容器是不会调用这个setApplicationContext的 @Override public void setApplicationContext(ApplicationContext applicationContext) { this.applicationContext = applicationContext; if (this.beanFactory == null) { this.beanFactory = applicationContext; } } Spring在完成这个Bean的初始化后,ScheduledAnnotationBeanPostProcessor类实现了ApplicationContextAware接口,所以直接调用了setApplicationContext方法将ApplicationContext上下文对象注入至该Bean对象(@EnableScheduling)中。然后在每个bean初始化之后就会去调用postProcessAfterInitialization方法(观察者模式)去会查找这个bean中任何带有@Scheduled的方法。 4、进入 postProcessAfterInitialization 方法: @Override public Object postProcessAfterInitialization(Object bean, String beanName) { if (bean instanceof AopInfrastructureBean || bean instanceof TaskScheduler || bean instanceof ScheduledExecutorService) { // Ignore AOP infrastructure such as scoped proxies. return bean; } Class<?> targetClass = AopProxyUtils.ultimateTargetClass(bean); if (!this.nonAnnotatedClasses.contains(targetClass)) { Map<Method, Set<Scheduled>> annotatedMethods = MethodIntrospector.selectMethods(targetClass, (MethodIntrospector.MetadataLookup<Set<Scheduled>>) method -> { Set<Scheduled> scheduledMethods = AnnotatedElementUtils.getMergedRepeatableAnnotations( method, Scheduled.class, Schedules.class); return (!scheduledMethods.isEmpty() ? scheduledMethods : null); }); if (annotatedMethods.isEmpty()) { this.nonAnnotatedClasses.add(targetClass); if (logger.isTraceEnabled()) { logger.trace("No @Scheduled annotations found on bean class: " + targetClass); } } else { // Non-empty set of methods annotatedMethods.forEach((method, scheduledMethods) -> scheduledMethods.forEach(scheduled -> processScheduled(scheduled, method, bean))); if (logger.isTraceEnabled()) { logger.trace(annotatedMethods.size() + " @Scheduled methods processed on bean '" + beanName + "': " + annotatedMethods); } } } return bean; } 找到带有@Scheduled注解的方法这个方法之后调用了processScheduled核心方法。按照这个思路往下追踪,定会明白其原理,此处给大家推荐一篇原理博客: [定时任务源码][Link 1] **三、@Scheduled注解中参数使用详解,使用重点** **1、首先看一下此注解包含哪些参数:** @Target({ElementType.METHOD, ElementType.ANNOTATION_TYPE}) @Retention(RetentionPolicy.RUNTIME) @Documented @Repeatable(Schedules.class) public @interface Scheduled { String cron() default ""; String zone() default ""; long fixedDelay() default -1L; String fixedDelayString() default ""; long fixedRate() default -1L; String fixedRateString() default ""; long initialDelay() default -1L; String initialDelayString() default ""; } 源码可见此注解可以添加八个参数,下面我们一一详解 **2、cron** 该参数接收一个cron表达式,cron表达式是一个字符串,字符串以5或6个空格隔开,分开共6或7个域,每一个域代表一个含义。 **cron表达式语法** **\[秒\] \[分\] \[小时\] \[日\] \[月\] \[周\] \[年\]** 注:\[年\]不是必须的域,可以省略\[年\],spring 3.0版本之后变成6个域 ![watermark_type_ZmFuZ3poZW5naGVpdGk_shadow_10_text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L25hbmRhbzE1OA_size_16_color_FFFFFF_t_70][] **通配符说明** 1、\*表示所有值。 例如:在分的字段上设置 \*,表示每一分钟都会触发。 2、? 表示不指定值。使用的场景为不需要关心当前设置这个字段的值。例如:要在每月的10号触发一个操作,但不关心是周几,所以需要周位置的那个字段设置为”?” 具体设置为 0 0 0 10 \* ? 3、-表示区间。例如 在小时上设置 “10-12”,表示 10,11,12点都会触发。 4、, 表示指定多个值,例如在周字段上设置 “MON,WED,FRI” 表示周一,周三和周五触发 5、/ 用于递增触发。如在秒上面设置”5/15” 表示从5秒开始,每增15秒触发(5,20,35,50)。 在月字段上设置’1/3’所示每月1号开始,每隔三天触发一次。 6、L 表示最后的意思。在日字段设置上,表示当月的最后一天(依据当前月份,如果是二月还会依据是否是润年\[leap\]), 在周字段上表示星期六,相当于”7”或”SAT”。如果在”L”前加上数字,则表示该数据的最后一个。例如在周字段上设置”6L”这样的格式,则表示“本月最后一个星期五” 7、W 表示离指定日期的最近那个工作日(周一至周五). 例如在日字段上置”15W”,表示离每月15号最近的那个工作日触发。如果15号正好是周六,则找最近的周五(14号)触发, 如果15号是周未,则找最近的下周一(16号)触发.如果15号正好在工作日(周一至周五),则就在该天触发。如果指定格式为 “1W”,它则表示每月1号往后最近的工作日触发。如果1号正是周六,则将在3号下周一触发。(注,”W”前只能设置具体的数字,不允许区间”-“)。 8、\#序号(表示每月的第几个周几),例如在周字段上设置”6\#3”表示在每月的第三个周六.注意如果指定”\#5”,正好第五周没有周六,则不会触发该配置(用在母亲节和父亲节再合适不过了) ;小提示:’L’和 ‘W’可以一组合使用。如果在日字段上设置”LW”,则表示在本月的最后一个工作日触发;周字段的设置,若使用英文字母是不区分大小写的,即MON与mon相同。 **示例** 每隔5秒执行一次:\*/5 \* \* \* \* ? 每隔1分钟执行一次:0 \*/1 \* \* \* ? 每天23点执行一次:0 0 23 \* \* ? 每天凌晨1点执行一次:0 0 1 \* \* ? 每月1号凌晨1点执行一次:0 0 1 1 \* ? 每月最后一天23点执行一次:0 0 23 L \* ? 每周星期天凌晨1点实行一次:0 0 1 ? \* L 在26分、29分、33分执行一次:0 26,29,33 \* \* \* ? 每天的0点、13点、18点、21点都执行一次:0 0 0,13,18,21 \* \* ? ## 2. zone ## 时区,接收一个java.util.TimeZone\#ID。cron表达式会基于该时区解析。默认是一个空字符串,即取服务器所在地的时区。比如我们一般使用的时区Asia/Shanghai。该字段我们一般留空。 ## 3. fixedDelay ## 上一次执行完毕时间点之后多长时间再执行。如: @Scheduled(fixedDelay = 5000) //上一次执行完毕时间点之后5秒再执行 ## 4. fixedDelayString ## 与 3. fixedDelay 意思相同,只是使用字符串的形式。唯一不同的是支持占位符。如: @Scheduled(fixedDelayString = "5000") //上一次执行完毕时间点之后5秒再执行 占位符的使用(配置文件中有配置:time.fixedDelay=5000): @Scheduled(fixedDelayString = "${time.fixedDelay}") ## 5. fixedRate ## 上一次开始执行时间点之后多长时间再执行。如: @Scheduled(fixedRate = 5000) //上一次开始执行时间点之后5秒再执行 ## 6. fixedRateString ## 与 5. fixedRate 意思相同,只是使用字符串的形式。唯一不同的是支持占位符。 ## 7. initialDelay ## 第一次延迟多长时间后再执行。如 //第一次延迟1秒后执行,之后按fixedRate的规则每5秒执行一次 @Scheduled(initialDelay=1000, fixedRate=5000) ## 8. initialDelayString ## 与7. initialDelay 意思相同,只是使用字符串的形式。唯一不同的是支持占位符。 到此,定时任务分析完成,不明白的小伙伴可以留言。 [Link 1]: https://blog.csdn.net/LDSWAN0/article/details/106097269 [watermark_type_ZmFuZ3poZW5naGVpdGk_shadow_10_text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L25hbmRhbzE1OA_size_16_color_FFFFFF_t_70]: /images/20221024/4b0e426382fb47da8013432d3309143d.png
还没有评论,来说两句吧...