任务调度


此篇指南将带你走进使用Spring的任务调度的步骤。

What You Will Build

你将会构建一个使用Spring的@Scheduled注解每五秒就打印输出当前时间的应用程序。

What You Need

  • 大约15分钟
  • 你喜欢的文本编辑器或IDE
  • JDK 1.8 以上
  • Graddle 4+ 或 Maven 3.2+
  • 你也可以直接将代码导入进你的IDE
    • Spring Tool Suite (STS)
    • InteelliJ IDEA

How to complete this guide

正如Spring大多数指南一样,你可以从头开始并且完成每一个步骤或者你可以绕开你已经熟悉的基本设置。无论哪种方式,你最终都是完成代码。

为了从头开始,移步到Starting with Spring Initializr

为了跳过基础,做如下步骤:

  • 下载并解压这篇指南的原仓库,或者使用GIt克隆git clone https://github.com/spring-guides/gs-scheduling-tasks.git
  • 进入(cd)gs-scheduling-tasks/initial
  • 移步到Create a Scheduled Task

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

Starting with Spring Initializr

你可以使用预初始化项目点击Generate来下载ZIP文件。这一项目被配置为适合本篇指南。

为了手动初始化项目:

  1. 浏览https://start.spring.io/。这个服务拉取了你的应用所有需要的依赖并且已经为了做了多数配置。
  2. 选择Gradle或Maven与你想使用的语言。本文假设你选择Java。
  3. 点击Generate
  4. 下载ZIP文件,这是一个为你的选择配置好的网络应用文件。

如果你的IDE整合了Spring Initializr,你可以从你的IDE完成此步骤

你也可以从GitHub中fork此项目使用你的IDE或者编辑器打开。

Adding the awaitility Dependency

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文件的完整内容:

<?xml version="1.0" encoding="UTF-8"?>

	4.0.0
	
		org.springframework.boot
		spring-boot-starter-parent
		2.6.3
		 
	
	com.example
	scheduling-tasks-complete
	0.0.1-SNAPSHOT
	scheduling-tasks-complete
	Demo project for Spring Boot

	
		1.8
	

	
		
			org.springframework.boot
			spring-boot-starter
		
		
			org.awaitility
			awaitility
			3.1.2
			test
		

		
			org.springframework.boot
			spring-boot-starter-test
			test
		
	

	
		
			
				org.springframework.boot
				spring-boot-maven-plugin
			
		
	


若要添加awaitility库到Gradle,添加如下依赖:

	testImplementation 'org.awaitility:awaitility:3.1.2'

一下展示了完整的build.gradle文件:

plugins {
	id 'org.springframework.boot' version '2.6.3'
	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()
}

Create a Scheduled Task

至此你已经设置好你的项目了,你可以创建一个计划任务。下面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="...")表达更多复杂的任务调度。

Enable Scheduling

尽管计划任务可以被嵌入到web应用和WAR文件中,更简单的方法(如下所示)创建了一个独立的(standlone)应用。为了这么做,将所有东西打包进一个单一的、可执行的JAR文件,由老旧的Javamain()方法驱动。来自于src/main/java/com/example/schedulingtasks/SchedulingTasksApplication.java展示了应用类:

package com.example.schedulingtasks;

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

@SpringBootApplication
@EnableScheduling
public class SchedulingTasksApplication {

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

@SpringBootApplication是一个添加了如下展示的所有内容的方便注解:

  • @Configuration:对于应用上下文(context),将类标记为bean定义的来源。
  • @EnableAutoConfiguration:告诉Spring Boot开始根据类路径设置添加bean,其它bean,以及各种属性设置。例如,如果spring-webmvc在类路径中,这一注解将应用程序标记为web应用以及激活关键行为,例如设置DispatcherServlet
  • @ComponentScan:告诉Spring寻找com.example包下其它组件、配置以及服务,使其找到控制器。

main()方法使用Spring Boot的SpringApplication.run()方法来启动一个应用程序。你是否注意到没有一行的XML?也同样没有web.xml文件。这一个应用程序是100%纯Java并且你并没有必须处理配置任何一个plumbing或infrastructure。

@EnableScheduling注解确保后台任务执行器(background task executor)被创建。如果没有它,将不会有东西被调度。

Build an executable JAR

你可以在命令行以Gradle或Maven运行应用程序。你也可以构建一个单一可执行的JAR包,其中包含所有必须的依赖、类以及资源并且运行。构建一个可执行jar可以易于传输、版本和部署服务作为应用,贯穿至整个开发周期,穿插于不同环境等等。

如果你使用Gradle,你可以通过使用./gradlew bootRun来运行应用程序。或者说,你可以使用./gradlew build来构建JAR包,然后运行JAR包,如下命令:

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

如果你使用Maven,你可以通过./mvnw spring-boot:run来运行应用程序。或者说,你可以使用./mvnw clean package来构建JAR包,通过如下命令执行JAR包。

java -jar target/gs-scheduling-tasks-0.1.0.jar

此处步骤描述了创建一个可执行JAR包。你也可以构造一个经典的WAR文件。

日志输出被展示,并且你可以看到在后台线程(background thread)的日志。每过五秒,你应该会看到你的计划任务。典型输出如下:

2022-04-29 09:23:04.348  INFO 8674 --- [   scheduling-1] c.e.schedulingtasks.ScheduledTasks       : The time is now 09:23:04
2022-04-29 09:23:09.348  INFO 8674 --- [   scheduling-1] c.e.schedulingtasks.ScheduledTasks       : The time is now 09:23:09
2022-04-29 09:23:14.348  INFO 8674 --- [   scheduling-1] c.e.schedulingtasks.ScheduledTasks       : The time is now 09:23:14