Spring Boot - 定時任務



排程是為特定時間段執行任務的過程。Spring Boot 為在 Spring 應用程式上編寫排程程式提供了良好的支援。

Java Cron 表示式

Java Cron 表示式用於配置 CronTrigger 的例項,CronTrigger 是 org.quartz.Trigger 的子類。有關 Java cron 表示式的更多資訊,您可以參考此連結:

https://docs.oracle.com/cd/E12058_01/doc/doc.1014/e12030/cron_expressions.htm

@EnableScheduling 註解用於為您的應用程式啟用排程程式。此註解應新增到主 Spring Boot 應用程式類檔案。

DemoApplication.java

package com.tutorialspoint.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;

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

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
   <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
   <modelVersion>4.0.0</modelVersion>
   <parent>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-parent</artifactId>
      <version>3.3.3</version>
      <relativePath/> <!-- lookup parent from repository -->
   </parent>
   <groupId>com.tutorialspoint</groupId>
   <artifactId>demo</artifactId>
   <version>0.0.1-SNAPSHOT</version>
   <name>demo</name>
   <description>Demo project for Spring Boot</description>
   <url/>
   <licenses>
      <license/>
   </licenses>
   <developers>
      <developer/>
   </developers>
   <scm>
      <connection/>
      <developerConnection/>
      <tag/>
      <url/>
   </scm>
   <properties>
      <java.version>21</java.version>
   </properties>
   <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>
   <build>
      <plugins>
         <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
         </plugin>
      </plugins>
   </build>
</project>

@Scheduled 註解用於為特定時間段觸發排程程式。

@Scheduled(cron = "0 0-5 13 * * ?")
public void cronJobSch() throws Exception {
}

以下是一個示例程式碼,演示瞭如何在接下來的五分鐘內,從下午 1:00 開始,每分鐘執行一次任務。

Scheduler.java

package com.tutorialspoint.demo.scheduler;

import java.text.SimpleDateFormat;
import java.util.Date;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

@Component
public class Scheduler {
   @Scheduled(cron = "0 0-5 13 * * ?")
   public void cronJobSch() {
      SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
      Date now = new Date();
      String strDate = sdf.format(now);
      System.out.println("Java cron job expression:: " + strDate);
   }
}

輸出

以下螢幕截圖顯示了應用程式如何在 13:03:00 啟動,並且從該時間起每分鐘執行一次 cron 作業排程程式任務,根據 cron 作業表示式,它將在接下來的五分鐘內執行。

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/

[32m :: Spring Boot :: [39m              [2m (v3.3.3)[0;39m

[2024-09-10T13:02:12Z] [org.springframework.boot.StartupInfoLogger] [main] [50] [INFO ] Starting DemoApplication using Java 21.0.3 with PID 13256 (E:\Dev\demo\target\classes started by Tutorialspoint in E:\Dev\demo)
[2024-09-10T13:02:12Z] [org.springframework.boot.SpringApplication] [main] [654] [INFO ] No active profile set, falling back to 1 default profile: "default"
[2024-09-10T13:02:13Z] [org.springframework.boot.StartupInfoLogger] [main] [56] [INFO ] Started DemoApplication in 1.043 seconds (process running for 1.995)
Java cron job expression:: 2024-09-10 13:03:00.091
Java cron job expression:: 2024-09-10 13:04:00.013
Java cron job expression:: 2024-09-10 13:05:00.015

固定速率

固定速率排程程式用於在特定時間執行任務。它不會等待上一個任務完成。值應以毫秒為單位。示例程式碼如下所示:

@Scheduled(fixedRate = 1000)
public void fixedRateSch() { 
}

以下是一個示例程式碼,演示瞭如何在應用程式啟動後每秒執行一次任務:

Scheduler.java

package com.tutorialspoint.demo.scheduler;

import java.text.SimpleDateFormat;
import java.util.Date;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

@Component
public class Scheduler {
   @Scheduled(fixedRate = 1000)
   public void fixedRateSch() {
      SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");

      Date now = new Date();
      String strDate = sdf.format(now);
      System.out.println("Fixed Rate scheduler:: " + strDate);
   }
}

輸出

觀察以下螢幕截圖,它顯示了應用程式在 13:06:45 啟動,之後每秒執行一次固定速率排程程式任務。

Fixed Rate scheduler:: 2024-09-10 13:06:45.832
Fixed Rate scheduler:: 2024-09-10 13:06:46.813
Fixed Rate scheduler:: 2024-09-10 13:06:47.809

固定延遲

固定延遲排程程式用於在特定時間執行任務。它應該等待上一個任務完成。值應以毫秒為單位。示例程式碼如下所示:

@Scheduled(fixedDelay = 1000, initialDelay = 1000)
public void fixedDelaySch() {
}

這裡,initialDelay 是任務在初始延遲值後第一次執行的時間。

以下示例演示瞭如何在應用程式啟動完成後 3 秒後,每秒執行一次任務:

Scheduler.java

package com.tutorialspoint.demo.scheduler;

import java.text.SimpleDateFormat;
import java.util.Date;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

@Component
public class Scheduler {
   @Scheduled(fixedDelay = 1000, initialDelay = 3000)
   public void fixedDelaySch() {
      SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
      Date now = new Date();
      String strDate = sdf.format(now);
      System.out.println("Fixed Delay scheduler:: " + strDate);
   }
}

輸出

觀察以下螢幕截圖,它顯示了應用程式在 13:11:42 啟動,並且每 3 秒執行一次固定延遲排程程式任務,每秒執行一次。

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/

[32m :: Spring Boot :: [39m              [2m (v3.3.3)[0;39m

[2024-09-10T13:11:42Z] [org.springframework.boot.StartupInfoLogger] [main] [50] [INFO ] Starting DemoApplication using Java 21.0.3 with PID 13660 (E:\Dev\demo\target\classes started by Tutorialspoint in E:\Dev\demo)
[2024-09-10T13:11:42Z] [org.springframework.boot.SpringApplication] [main] [654] [INFO ] No active profile set, falling back to 1 default profile: "default"
[2024-09-10T13:11:42Z] [org.springframework.boot.StartupInfoLogger] [main] [56] [INFO ] Started DemoApplication in 1.066 seconds (process running for 2.035)
Fixed Rate scheduler:: 2024-09-10 13:11:46.061
Fixed Rate scheduler:: 2024-09-10 13:11:47.063
Fixed Rate scheduler:: 2024-09-10 13:11:48.065

廣告