深度解析Spring 调度任务

本指南将引导您完成使用 Spring 安排任务的步骤。

image.png

你将建造什么

@Scheduled 您将构建一个应用程序,使用 Spring 的注释每五秒打印一次当前时间。

你需要什么

  • 约15分钟

  • 最喜欢的文本编辑器或 IDE

  • JDK 1.8或更高版本

  • Gradle 4+或Maven 3.2+

  • 您还可以将代码直接导入 IDE:

  • 弹簧工具套件 (STS)

  • IntelliJ IDEA

如何完成本指南

像大多数 Spring入门指南一样,您可以从头开始并完成每个步骤,也可以绕过您已经熟悉的基本设置步骤。无论哪种方式,您最终都会得到工作代码。

从头开始 ,请继续从 Spring Initializr 开始。

跳过基础知识 ,请执行以下操作:

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

完成后,您可以对照中的代码检查结果 gs-scheduling-tasks/complete

从 Spring Initializr 开始

您可以使用这个预先初始化的项目并单击 Generate 下载 ZIP 文件。此项目配置为适合本教程中的示例。

手动初始化项目:

  1. 导航到https://start.spring.io。该服务提取应用程序所需的所有依赖项,并为您完成大部分设置。
  2. 选择 Gradle 或 Maven 以及您要使用的语言。本指南假定您选择了 Java。
  3. 单击 生成
  4. 下载生成的 ZIP 文件,该文件是根据您的选择配置的 Web 应用程序的存档。

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

你也可以从 Github 上 fork 项目并在你的 IDE 或其他编辑器中打开它。

添加 awaitility 依赖项

中的测试 complete/src/test/java/com/example/schedulingtasks/ScheduledTasksTest.java 需要 awaitility 库。

更高版本的awaitility库不适用于此测试,因此您必须指定版本 3.1.2。

要将 awaitility 库添加到 Maven,请添加以下依赖项:


  org.awaitility
  awaitility
  3.1.2
  test
复制

以下清单显示了完成的 pom.xml 文件:


4.0.0org.springframework.bootspring-boot-starter-parent2.7.1 com.examplescheduling-tasks-complete0.0.1-SNAPSHOTscheduling-tasks-completeDemo project for Spring Boot

  1.8

  org.springframework.bootspring-boot-starterorg.awaitilityawaitility3.1.2test

    org.springframework.bootspring-boot-starter-testtest

  org.springframework.bootspring-boot-maven-plugin

复制

要将 awaitility 库添加到 Gradle,请添加以下依赖项:

testImplementation 'org.awaitility:awaitility:3.1.2'复制

以下清单显示了完成的 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()
}复制

创建计划任务

现在您已经设置了项目,您可以创建计划任务。以下清单(来自 src/main/java/com/example/schedulingtasks/ScheduledTasks.java )显示了如何执行此操作:

/*
 * 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()));}
}复制

注释定义了 Scheduled 特定方法何时运行。

此示例使用fixedRate,它指定方法调用之间的间隔,从每次调用的开始时间开始测量。还有其他选项,例如fixedDelay,它指定从任务完成开始测量的调用之间的间隔。您还可以使用@Scheduled(cron=". . .")表达式进行更复杂的任务调度。

整个开发生命周期、跨不同环境等中轻松地作为应用程序交付、版本化和部署服务。

如果您使用 Gradle,则可以使用 ./gradlew bootRun . 或者,您可以使用构建 JAR 文件 ./gradlew build ,然后运行 JAR 文件,如下所示:

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

如果您使用 Maven,则可以使用 ./mvnw spring-boot:run . 或者,您可以使用构建 JAR 文件, ./mvnw clean package 然后运行该 JAR 文件,如下所示:

java -jar 目标/gs-scheduling-tasks-0.1.0.jar

此处描述的步骤创建了一个可运行的 JAR。您还可以构建经典的 WAR 文件。

显示日志输出,您可以从日志中看到它在后台线程上。您应该看到您的计划任务每五秒触发一次。以下清单显示了典型输出:

 --- [   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
...复制

概括

恭喜!您创建了一个带有计划任务的应用程序。此外,此技术适用于任何类型的应用程序。

你可能感兴趣的:(深度解析Spring 调度任务)