Spring Boot2 實戰系列之Scheduling Tasks

前言

在系統中使用定時任務已經是一個比較常見的事情,比如需要定時發送郵件報告,生成系統日誌,進行數據歸檔等。Spring3.0 起加入了任務調度功能 Schedule, 它不需要使用依賴其他 JAR 包,使用起來比較方便。

在 SpringBoot 中使用 scheduled,在項目啓動類上添加註解 @EnableScheduling 來開啓任務調度,然後在方法上使用註解 @Scheduled

    @Scheduled(fixedRate = 5000)
    public void fixedRate() {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        log.info("The time is now {}", dateFormat.format(new Date()));
    }

    @Scheduled(fixedDelay = 5000)
    public void fixedDelay() {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        log.info("The time is now {}", dateFormat.format(new Date()));
    }

    @Scheduled(initialDelay = 5000, fixedDelay = 5000)
    public void initialDelay() {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        log.info("The time is now {}", dateFormat.format(new Date()));
    }

    @Scheduled(cron = "0/10 * * * * *")
    public void reportCurrentTime() {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        log.info("The time is now {}", dateFormat.format(new Date()));
    }

注意到這裏有幾個常用的 Scheduled 參數:

  • fixedRate:每間隔多長時間調用一次該方法
  • fixedDelay: 上一次任務完成後,間隔多長時間調用該方法
  • initialDelay:首次任務啓動延遲多長時間
  • cron: 按照指定的表達式實行更精細的任務調度

Cron 每個域的含義爲:{秒} {分} {時} {日} {月} {周},對應的範圍如下:

範圍 可用的特殊字符
0-59 , - * /
0-59 , - * /
0-23 , - * /
1-31 , - * / ?
1-12 或 JAN-DEC , - * /
0-7(0和7都是星期天) 或 SUN-SAT , - * / ?

Cron 使用例子

cron 表達式 含義
0 0 * * * * 每小時執行一次
*/10 * * * * * 每10秒執行一次
0 0 8-10 * * * 每天 8,9,10點執行一次
0 0 6,19 * * * 每天上午6點和下午7點執行一次
0 0/30 8-10 * * * 每天8:00, 8:30, 9:00, 9:30, 10:00, 10:30 執行一次
0 0 9-17 * * MON-FRI 工作日上午9點到下午5點每小時執行一次
0 0 0 25 12 ? 每個聖誕節的午夜觸發一次

注意上面用到的特殊字符:, - * / ?,它們的含義是:

  • ",": 表示枚舉多個值
  • "-":表示範圍
  • "*": 匹配該域的任意值
  • "/": 表示從起始時間觸發一次後每隔多長時間執行一次
  • "?": 只能在日和周域使用, 表示不明確的值,作用和 “*” 一樣,匹配任意值

創建項目

項目結構圖如下:
在這裏插入圖片描述
pom 依賴文件如下:

<?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>2.2.5.RELEASE</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>
	<groupId>top.yekongle</groupId>
	<artifactId>springboot-scheduled-sample</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>springboot-scheduled-sample</name>
	<description>Scheduled project for Spring Boot</description>

	<properties>
		<java.version>1.8</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-devtools</artifactId>
			<scope>runtime</scope>
			<optional>true</optional>
		</dependency>
		<dependency>
			<groupId>org.projectlombok</groupId>
			<artifactId>lombok</artifactId>
			<optional>true</optional>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
			<exclusions>
				<exclusion>
					<groupId>org.junit.vintage</groupId>
					<artifactId>junit-vintage-engine</artifactId>
				</exclusion>
			</exclusions>
		</dependency>
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>

</project>

代碼編寫

SpringbootScheduledSampleApplication.java, 項目啓動類

package top.yekongle.scheduled;

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

/**
 * @EnableScheduling 開啓任務調度
 * */
@SpringBootApplication
@EnableScheduling
public class SpringbootScheduledSampleApplication {

	public static void main(String[] args) {
		SpringApplication.run(SpringbootScheduledSampleApplication.class, args);
	}

}

ScheduledJob.java, 任務調度類

package top.yekongle.scheduled.job;

import java.text.SimpleDateFormat;
import java.util.Date;

import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import lombok.extern.slf4j.Slf4j;

@Component
@Slf4j
public class ScheduledJob {
	// 時間格式化
	private static final SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

	// 每5秒執行一次,無論上次任務執行結束與否,參數單位是毫秒
	@Scheduled(fixedRate = 5000)
	public void fixedRate() {
		log.info("fixedRate>>>:{}", format.format(new Date()));
	}

	// 當上次任務執行結束後,間隔5秒再執行下次任務,參數單位是毫秒
	@Scheduled(fixedDelay = 5000)
	public void fixedDelay() {
		log.info("fixedDelay>>>:{}", format.format(new Date()));
	}

	// initialDelay 表示首次任務啓動的延遲時間,參數單位是毫秒
	@Scheduled(initialDelay = 5000, fixedDelay = 5000)
	public void initialDelay() {
		log.info("initialDelay>>>:{}", format.format(new Date()));
	}

	// 使用cron表達式,可以按照cron的邏輯執行代碼, 實行更精細的任務調度
	// 每隔10秒執行一次
	@Scheduled(cron = "0/10 * * * * *")
	public void startJob() {
		log.info("Cron job:{}", format.format(new Date()));
	}

}

運行測試

在這裏插入圖片描述

項目已上傳至 Github: https://github.com/yekongle/springboot-code-samples/tree/master/springboot-scheduled-sample , 希望對小夥伴們有幫助哦。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章