Spring Boot (十一): Spring Boot 定時任務

  • 2019 年 10 月 12 日
  • 筆記

在實際的項目開發工作中,我們經常會遇到需要做一些定時任務的工作,那麼,在 Spring Boot 中是如何實現的呢?

1. 添加依賴

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

程式碼清單:spring-boot-scheduler/pom.xml
***

<dependencies>      <dependency>          <groupId>org.springframework.boot</groupId>          <artifactId>spring-boot-starter</artifactId>      </dependency>        <dependency>          <groupId>org.springframework.boot</groupId>          <artifactId>spring-boot-starter-test</artifactId>          <scope>test</scope>      </dependency>  </dependencies>

2. 配置文件

配置文件無需過多的配置:

程式碼清單:spring-boot-scheduler/src/main/resources/application.yml
***

server:    port: 8080  spring:    application:      name: spring-boot-scheduler

3. 啟動主類

啟動主類需增加註解 @EnableScheduling 表示我們要開啟定時任務這個服務。

程式碼清單:spring-boot-scheduler/src/main/java/com/springboot/springbootscheduler/SpringBootSchedulerApplication.java
***

@SpringBootApplication  @EnableScheduling  public class SpringBootSchedulerApplication {        public static void main(String[] args) {          SpringApplication.run(SpringBootSchedulerApplication.class, args);      }    }

4. 定時任務實現類

程式碼清單:spring-boot-scheduler/src/main/java/com/springboot/springbootscheduler/task/Task.java
***

@Component  public class Task {        private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");        private final Logger logger = LoggerFactory.getLogger(Task.class);        /**       * cron表達式       */      @Scheduled(cron = "*/5 * * * * ?")      private void task1() {          logger.info("task1 正在執行,現在時間:{}", dateFormat.format(new Date()));      }        /**       * 上一次開始執行時間點之後5秒再執行       */      @Scheduled(fixedRate = 5000)      public void task2() {          logger.info("task2 正在執行,現在時間:{}", dateFormat.format(new Date()));      }        /**       * 上一次執行完畢時間點之後5秒再執行       */      @Scheduled(fixedDelay = 5000)      public void task3() {          logger.info("task3 正在執行,現在時間:{}", dateFormat.format(new Date()));      }        /**       * 第一次延遲1秒後執行,之後按fixedRate的規則每5秒執行一次       */      @Scheduled(initialDelay = 1000, fixedRate = 5000)      public void task4() {          logger.info("task4 正在執行,現在時間:{}", dateFormat.format(new Date()));      }  }

4.1 參數 cron

cron表達式語法:

[秒] [分] [小時] [日] [月] [周] [年]

註:[年]不是必須的域,可以省略[年],則一共6個域

說明 必填 允許填寫的值 允許的通配符
0-59 , – * /
0-59 , – * /
0-23 , – * /
1-31 , – * ? / L W
1-12 / JAN-DEC , – * /
1-7 or SUN-SAT , – * ? / L #
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 註解的使用方式其實在源碼里已經講的很清楚了,這裡附上供大家參考:

@Target({ElementType.METHOD, ElementType.ANNOTATION_TYPE})  @Retention(RetentionPolicy.RUNTIME)  @Documented  @Repeatable(Schedules.class)  public @interface Scheduled {        /**       * A special cron expression value that indicates a disabled trigger: {@value}.       * <p>This is primarily meant for use with ${...} placeholders, allowing for       * external disabling of corresponding scheduled methods.       * @since 5.1       */      String CRON_DISABLED = "-";          /**       * A cron-like expression, extending the usual UN*X definition to include triggers       * on the second as well as minute, hour, day of month, month and day of week.       * <p>E.g. {@code "0 * * * * MON-FRI"} means once per minute on weekdays       * (at the top of the minute - the 0th second).       * <p>The special value {@link #CRON_DISABLED "-"} indicates a disabled cron trigger,       * primarily meant for externally specified values resolved by a ${...} placeholder.       * @return an expression that can be parsed to a cron schedule       * @see org.springframework.scheduling.support.CronSequenceGenerator       */      String cron() default "";        /**       * A time zone for which the cron expression will be resolved. By default, this       * attribute is the empty String (i.e. the server's local time zone will be used).       * @return a zone id accepted by {@link java.util.TimeZone#getTimeZone(String)},       * or an empty String to indicate the server's default time zone       * @since 4.0       * @see org.springframework.scheduling.support.CronTrigger#CronTrigger(String, java.util.TimeZone)       * @see java.util.TimeZone       */      String zone() default "";        /**       * Execute the annotated method with a fixed period in milliseconds between the       * end of the last invocation and the start of the next.       * @return the delay in milliseconds       */      long fixedDelay() default -1;        /**       * Execute the annotated method with a fixed period in milliseconds between the       * end of the last invocation and the start of the next.       * @return the delay in milliseconds as a String value, e.g. a placeholder       * or a {@link java.time.Duration#parse java.time.Duration} compliant value       * @since 3.2.2       */      String fixedDelayString() default "";        /**       * Execute the annotated method with a fixed period in milliseconds between       * invocations.       * @return the period in milliseconds       */      long fixedRate() default -1;        /**       * Execute the annotated method with a fixed period in milliseconds between       * invocations.       * @return the period in milliseconds as a String value, e.g. a placeholder       * or a {@link java.time.Duration#parse java.time.Duration} compliant value       * @since 3.2.2       */      String fixedRateString() default "";        /**       * Number of milliseconds to delay before the first execution of a       * {@link #fixedRate()} or {@link #fixedDelay()} task.       * @return the initial delay in milliseconds       * @since 3.2       */      long initialDelay() default -1;        /**       * Number of milliseconds to delay before the first execution of a       * {@link #fixedRate()} or {@link #fixedDelay()} task.       * @return the initial delay in milliseconds as a String value, e.g. a placeholder       * or a {@link java.time.Duration#parse java.time.Duration} compliant value       * @since 3.2.2       */      String initialDelayString() default "";    }

5. 示例程式碼

示例程式碼-Github

示例程式碼-Gitee

6. 參考

https://www.jianshu.com/p/1defb0f22ed1