`
公园美丽
  • 浏览: 11768 次
社区版块
存档分类
最新评论

Spring Boot : Spring Boot 定时任务

 
阅读更多

 

Spring Boot (十一): Spring Boot 定时任务
 

 

在实际的项目开发工作中,我们经常会遇到需要做一些定时任务的工作,那么,在 Spring Boot 中是如何实现的呢?

1. 添加依赖

在 pom.xml 文件中只需引入 spring-boot-starter 的依赖即可:

代码清单:spring-boot-scheduler/pom.xml

Java代码  收藏代码
  1. <dependencies>  
  2.     <dependency>  
  3.         <groupId>org.springframework.boot</groupId>  
  4.         <artifactId>spring-boot-starter</artifactId>  
  5.     </dependency>  
  6.   
  7.     <dependency>  
  8.         <groupId>org.springframework.boot</groupId>  
  9.         <artifactId>spring-boot-starter-test</artifactId>  
  10.         <scope>test</scope>  
  11.     </dependency>  
  12. </dependencies>  

 2. 配置文件

配置文件无需过多的配置:

代码清单:spring-boot-scheduler/src/main/resources/application.yml

Java代码  收藏代码
  1. server:  
  2.   port: 8080  
  3. spring:  
  4.   application:  
  5.     name: spring-boot-scheduler  

 3. 启动主类

启动主类需增加注解 @EnableScheduling 表示我们要开启定时任务这个服务。

代码清单:spring-boot-scheduler/src/main/java/com/springboot/springbootscheduler/SpringBootSchedulerApplication.java

Java代码  收藏代码
  1. @SpringBootApplication  
  2. @EnableScheduling  
  3. public class SpringBootSchedulerApplication {  
  4.   
  5.     public static void main(String[] args) {  
  6.         SpringApplication.run(SpringBootSchedulerApplication.class, args);  
  7.     }  
  8.   
  9. }  

 

4. 定时任务实现类

代码清单:spring-boot-scheduler/src/main/java/com/springboot/springbootscheduler/task/Task.java

Java代码  收藏代码
  1. @Component  
  2. public class Task {  
  3.   
  4.     private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");  
  5.   
  6.     private final Logger logger = LoggerFactory.getLogger(Task.class);  
  7.   
  8.     /** 
  9.      * cron表达式 
  10.      */  
  11.     @Scheduled(cron = "*/5 * * * * ?")  
  12.     private void task1() {  
  13.         logger.info("task1 正在执行,现在时间:{}", dateFormat.format(new Date()));  
  14.     }  
  15.   
  16.     /** 
  17.      * 上一次开始执行时间点之后5秒再执行 
  18.      */  
  19.     @Scheduled(fixedRate = 5000)  
  20.     public void task2() {  
  21.         logger.info("task2 正在执行,现在时间:{}", dateFormat.format(new Date()));  
  22.     }  
  23.   
  24.     /** 
  25.      * 上一次执行完毕时间点之后5秒再执行 
  26.      */  
  27.     @Scheduled(fixedDelay = 5000)  
  28.     public void task3() {  
  29.         logger.info("task3 正在执行,现在时间:{}", dateFormat.format(new Date()));  
  30.     }  
  31.   
  32.     /** 
  33.      * 第一次延迟1秒后执行,之后按fixedRate的规则每5秒执行一次 
  34.      */  
  35.     @Scheduled(initialDelay = 1000, fixedRate = 5000)  
  36.     public void task4() {  
  37.         logger.info("task4 正在执行,现在时间:{}", dateFormat.format(new Date()));  
  38.     }  
  39. }  

 4.1 参数 cron

cron表达式语法:

Java代码  收藏代码
  1. [秒] [分] [小时] [日] [月] [周] [年]  

 注:[年]不是必须的域,可以省略[年],则一共6个域

Java代码  收藏代码
  1. 说明  必填  允许填写的值  允许的通配符  
  2. 秒   是   0-59    , – * /  
  3. 分   是   0-59    , – * /  
  4. 时   是   0-23    , – * /  
  5. 日   是   1-31    , – * ? / L W  
  6. 月   是   1-12 / JAN-DEC  , – * /  
  7. 周   是   1-7 or SUN-SAT  , – * ? / L #  
  8. 年   否   1970-2099   , – * /  

 通配符说明:

  • * 表示所有值。 例如:在分的字段上设置 *,表示每一分钟都会触发。
  • ? 表示不指定值。使用的场景为不需要关心当前设置这个字段的值。例如:要在每月的10号触发一个操作,但不关心是周几,所以需要周位置的那个字段设置为”?” 具体设置为 0 0 0 10 * ?
  • - 表示区间。例如 在小时上设置 “10-12”,表示 10,11,12点都会触发。
  • , 表示指定多个值,例如在周字段上设置 “MON,WED,FRI” 表示周一,周三和周五触发
  • / 用于递增触发。如在秒上面设置”5/15” 表示从5秒开始,每增15秒触发(5,20,35,50)。 在月字段上设置’1/3’所示每月1号开始,每隔三天触发一次。
  • L 表示最后的意思。在日字段设置上,表示当月的最后一天(依据当前月份,如果是二月还会依据是否是润年[leap]), 在周字段上表示星期六,相当于”7”或”SAT”。如果在”L”前加上数字,则表示该数据的最后一个。例如在周字段上设置”6L”这样的格式,则表示“本月最后一个星期五”
  • W 表示离指定日期的最近那个工作日(周一至周五). 例如在日字段上置”15W”,表示离每月15号最近的那个工作日触发。如果15号正好是周六,则找最近的周五(14号)触发, 如果15号是周未,则找最近的下周一(16号)触发.如果15号正好在工作日(周一至周五),则就在该天触发。如果指定格式为 “1W”,它则表示每月1号往后最近的工作日触发。如果1号正是周六,则将在3号下周一触发。(注,”W”前只能设置具体的数字,不允许区间”-“)。
  • # 序号(表示每月的第几个周几),例如在周字段上设置”6#3”表示在每月的第三个周六.注意如果指定”#5”,正好第五周没有周六,则不会触发该配置(用在母亲节和父亲节再合适不过了) ;小提示:’L’和 ‘W’可以一组合使用。如果在日字段上设置”LW”,则表示在本月的最后一个工作日触发;周字段的设置,若使用英文字母是不区分大小写的,即MON与mon相同。

4.2 参数 zone

时区,接收一个java.util.TimeZone#ID。cron表达式会基于该时区解析。默认是一个空字符串,即取服务器所在地的时区。比如我们一般使用的时区Asia/Shanghai。该字段我们一般留空。

4.3 参数 fixedDelay 和 fixedDelayString

这两个参数其实含义是一样的,只是一个使用的是 Long 类型,一个使用的是 String 类型。

含义都是上一次执行完毕时间点之后多长时间再执行,具体使用示例在上面的代码中已经给出。

4.4 参数 fixedRate 和 fixedRateString

这一组参数和上面的那组参数也是一样的,同样的是类型不同,含义是上一次开始执行时间点之后多长时间再执行。

4.5 参数 initialDelay 和 initialDelayString

这组参数的含义是第一次延迟多长时间后再执行。

4.6 附上 org.springframework.scheduling.annotation.Scheduled

@Scheduled 注解的使用方式其实在源码里已经讲的很清楚了,这里附上供大家参考:

Java代码  收藏代码
  1. @Target({ElementType.METHOD, ElementType.ANNOTATION_TYPE})  
  2. @Retention(RetentionPolicy.RUNTIME)  
  3. @Documented  
  4. @Repeatable(Schedules.class)  
  5. public @interface Scheduled {  
  6.   
  7.     /** 
  8.      * A special cron expression value that indicates a disabled trigger: {@value}. 
  9.      * <p>This is primarily meant for use with ${...} placeholders, allowing for 
  10.      * external disabling of corresponding scheduled methods. 
  11.      * @since 5.1 
  12.      */  
  13.     String CRON_DISABLED = "-";  
  14.   
  15.     /** 
  16.      * A cron-like expression, extending the usual UN*X definition to include triggers 
  17.      * on the second as well as minute, hour, day of month, month and day of week. 
  18.      * <p>E.g. {@code "0 * * * * MON-FRI"} means once per minute on weekdays 
  19.      * (at the top of the minute - the 0th second). 
  20.      * <p>The special value {@link #CRON_DISABLED "-"} indicates a disabled cron trigger, 
  21.      * primarily meant for externally specified values resolved by a ${...} placeholder. 
  22.      * @return an expression that can be parsed to a cron schedule 
  23.      * @see org.springframework.scheduling.support.CronSequenceGenerator 
  24.      */  
  25.     String cron() default "";  
  26.   
  27.     /** 
  28.      * A time zone for which the cron expression will be resolved. By default, this 
  29.      * attribute is the empty String (i.e. the server's local time zone will be used). 
  30.      * @return a zone id accepted by {@link java.util.TimeZone#getTimeZone(String)}, 
  31.      * or an empty String to indicate the server's default time zone 
  32.      * @since 4.0 
  33.      * @see org.springframework.scheduling.support.CronTrigger#CronTrigger(String, java.util.TimeZone) 
  34.      * @see java.util.TimeZone 
  35.      */  
  36.     String zone() default "";  
  37.   
  38.     /** 
  39.      * Execute the annotated method with a fixed period in milliseconds between the 
  40.      * end of the last invocation and the start of the next. 
  41.      * @return the delay in milliseconds 
  42.      */  
  43.     long fixedDelay() default -1;  
  44.   
  45.     /** 
  46.      * Execute the annotated method with a fixed period in milliseconds between the 
  47.      * end of the last invocation and the start of the next. 
  48.      * @return the delay in milliseconds as a String value, e.g. a placeholder 
  49.      * or a {@link java.time.Duration#parse java.time.Duration} compliant value 
  50.      * @since 3.2.2 
  51.      */  
  52.     String fixedDelayString() default "";  
  53.   
  54.     /** 
  55.      * Execute the annotated method with a fixed period in milliseconds between 
  56.      * invocations. 
  57.      * @return the period in milliseconds 
  58.      */  
  59.     long fixedRate() default -1;  
  60.   
  61.     /** 
  62.      * Execute the annotated method with a fixed period in milliseconds between 
  63.      * invocations. 
  64.      * @return the period in milliseconds as a String value, e.g. a placeholder 
  65.      * or a {@link java.time.Duration#parse java.time.Duration} compliant value 
  66.      * @since 3.2.2 
  67.      */  
  68.     String fixedRateString() default "";  
  69.   
  70.     /** 
  71.      * Number of milliseconds to delay before the first execution of a 
  72.      * {@link #fixedRate()} or {@link #fixedDelay()} task. 
  73.      * @return the initial delay in milliseconds 
  74.      * @since 3.2 
  75.      */  
  76.     long initialDelay() default -1;  
  77.   
  78.     /** 
  79.      * Number of milliseconds to delay before the first execution of a 
  80.      * {@link #fixedRate()} or {@link #fixedDelay()} task. 
  81.      * @return the initial delay in milliseconds as a String value, e.g. a placeholder 
  82.      * or a {@link java.time.Duration#parse java.time.Duration} compliant value 
  83.      * @since 3.2.2 
  84.      */  
  85.     String initialDelayString() default "";  
  86.   
  87. }  

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics