深度解析Spring 調(diào)度任務(wù)

本指南將引導(dǎo)您完成使用 Spring 安排任務(wù)的步驟。

image.png

你將建造什么

@Scheduled 您將構(gòu)建一個應(yīng)用程序,使用 Spring 的注釋每五秒打印一次當(dāng)前時間。

你需要什么

  • 約15分鐘

  • 最喜歡的文本編輯器或 IDE

  • JDK 1.8或更高版本

  • Gradle 4+或Maven 3.2+

  • 您還可以將代碼直接導(dǎo)入 IDE:

  • 彈簧工具套件 (STS)

  • IntelliJ IDEA

如何完成本指南

像大多數(shù) Spring入門指南一樣,您可以從頭開始并完成每個步驟,也可以繞過您已經(jīng)熟悉的基本設(shè)置步驟。無論哪種方式,您最終都會得到工作代碼。

從頭開始 ,請繼續(xù)從 Spring Initializr 開始。

跳過基礎(chǔ)知識 ,請執(zhí)行以下操作:

git clone https://github.com/spring-guides/gs-scheduling-tasks.git
gs-scheduling-tasks/initial

完成后,您可以對照中的代碼檢查結(jié)果 gs-scheduling-tasks/complete 。

從 Spring Initializr 開始

您可以使用這個預(yù)先初始化的項(xiàng)目并單擊 Generate 下載 ZIP 文件。此項(xiàng)目配置為適合本教程中的示例。

手動初始化項(xiàng)目:

  1. 導(dǎo)航到https://start.spring.io。該服務(wù)提取應(yīng)用程序所需的所有依賴項(xiàng),并為您完成大部分設(shè)置。
  2. 選擇 Gradle 或 Maven 以及您要使用的語言。本指南假定您選擇了 Java。
  3. 單擊 生成
  4. 下載生成的 ZIP 文件,該文件是根據(jù)您的選擇配置的 Web 應(yīng)用程序的存檔。

如果您的 IDE 具有 Spring Initializr 集成,您可以從您的 IDE 完成此過程。

你也可以從 Github 上 fork 項(xiàng)目并在你的 IDE 或其他編輯器中打開它。

添加 awaitility 依賴項(xiàng)

中的測試 complete/src/test/java/com/example/schedulingtasks/ScheduledTasksTest.java 需要 awaitility 庫。

更高版本的awaitility庫不適用于此測試,因此您必須指定版本 3.1.2。

要將 awaitility 庫添加到 Maven,請?zhí)砑右韵乱蕾図?xiàng):

<dependency>
  <groupId>org.awaitility</groupId>
  <artifactId>awaitility</artifactId>
  <version>3.1.2</version>
  <scope>test</scope>
</dependency>復(fù)制

以下清單顯示了完成的 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>2.7.1</version><relativePath/> <!-- lookup parent from repository --></parent><groupId>com.example</groupId><artifactId>scheduling-tasks-complete</artifactId><version>0.0.1-SNAPSHOT</version><name>scheduling-tasks-complete</name><description>Demo 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.awaitility</groupId><artifactId>awaitility</artifactId><version>3.1.2</version><scope>test</scope></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>復(fù)制

要將 awaitility 庫添加到 Gradle,請?zhí)砑右韵乱蕾図?xiàng):

testImplementation 'org.awaitility:awaitility:3.1.2'復(fù)制

以下清單顯示了完成的 build.gradle 文件:

plugins {
  id 'org.springframework.boot' version '2.7.1'
  id 'io.spring.dependency-management' version '1.0.11.RELEASE'
  id 'java'
}

group = 'com.example'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '1.8'

repositories {
  mavenCentral()
}

dependencies {
  implementation 'org.springframework.boot:spring-boot-starter'
  testImplementation 'org.awaitility:awaitility:3.1.2'
  testImplementation('org.springframework.boot:spring-boot-starter-test')
}

test {
  useJUnitPlatform()
}復(fù)制

創(chuàng)建計(jì)劃任務(wù)

現(xiàn)在您已經(jīng)設(shè)置了項(xiàng)目,您可以創(chuàng)建計(jì)劃任務(wù)。以下清單(來自 src/main/java/com/example/schedulingtasks/ScheduledTasks.java )顯示了如何執(zhí)行此操作:

/*
 * Copyright 2012-2015 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.example.schedulingtasks;

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

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

@Component
public class ScheduledTasks {

  private static final Logger log = LoggerFactory.getLogger(ScheduledTasks.class);

  private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");

  @Scheduled(fixedRate = 5000)public void reportCurrentTime() {
    log.info("The time is now {}", dateFormat.format(new Date()));}
}復(fù)制

注釋定義了 Scheduled 特定方法何時運(yùn)行。

此示例使用fixedRate,它指定方法調(diào)用之間的間隔,從每次調(diào)用的開始時間開始測量。還有其他選項(xiàng),例如fixedDelay,它指定從任務(wù)完成開始測量的調(diào)用之間的間隔。您還可以使用@Scheduled(cron=". . .")表達(dá)式進(jìn)行更復(fù)雜的任務(wù)調(diào)度。

整個開發(fā)生命周期、跨不同環(huán)境等中輕松地作為應(yīng)用程序交付、版本化和部署服務(wù)。

如果您使用 Gradle,則可以使用 ./gradlew bootRun . 或者,您可以使用構(gòu)建 JAR 文件 ./gradlew build ,然后運(yùn)行 JAR 文件,如下所示:

java -jar build/libs/gs-scheduling-tasks-0.1.0.jar

如果您使用 Maven,則可以使用 ./mvnw spring-boot:run . 或者,您可以使用構(gòu)建 JAR 文件, ./mvnw clean package 然后運(yùn)行該 JAR 文件,如下所示:

java -jar 目標(biāo)/gs-scheduling-tasks-0.1.0.jar

此處描述的步驟創(chuàng)建了一個可運(yùn)行的 JAR。您還可以構(gòu)建經(jīng)典的 WAR 文件。

顯示日志輸出,您可以從日志中看到它在后臺線程上。您應(yīng)該看到您的計(jì)劃任務(wù)每五秒觸發(fā)一次。以下清單顯示了典型輸出:

 --- [   scheduling-1] c.e.schedulingtasks.ScheduledTasks       : The time is now 12:07:35
2019-10-02 12:07:40.659  INFO 28617 --- [   scheduling-1] c.e.schedulingtasks.ScheduledTasks       : The time is now 12:07:40
2019-10-02 12:07:45.659  INFO 28617 --- [   scheduling-1] c.e.schedulingtasks.ScheduledTasks       : The time is now 12:07:45
2019-10-02 12:07:50.657  INFO 28617 --- [   scheduling-1] c.e.schedulingtasks.ScheduledTasks       : The time is now 12:07:50
...復(fù)制

概括

恭喜!您創(chuàng)建了一個帶有計(jì)劃任務(wù)的應(yīng)用程序。此外,此技術(shù)適用于任何類型的應(yīng)用程序。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容