SpringBoot定时任务

原文链接: https://spring.io/guides/gs/scheduling-tasks/

Scheduling Tasks(定时任务)

This guide walks you through the steps for scheduling tasks with Spring.
这篇指南将会向你介绍Spring定时任务。

What you’ll build(你将构建什么)

You’ll build an application that prints out the current time every five seconds using Spring’s @Scheduled annotation.
你将会使用Spring的@Scheduled注解构建一个每五分钟输出当前时间的应用。

What you’ll need(你需要什么)

  • About 15 minutes
  • A favorite text editor or IDE
  • JDK 1.8 or later
  • Gradle 4+ or Maven 3.2+
  • You can also import the code straight into your IDE:
  • Spring Tool Suite (STS)
  • IntelliJ IDEA

How to complete this guide(如何完成这篇指南)

Like most Spring Getting Started guides, you can start from scratch and complete each step or you can bypass basic setup steps that are already familiar to you. Either way, you end up with working code.
就像大部分的Spring开始指南,你可以从零开始完成每一步或者跳过那些你熟悉的步骤。无论如何,你都能够完成这份代码。

Create a scheduled task(创建一个定时任务)

Now that you’ve set up your project, you can create a scheduled task.
现在你建立一个项目,你可以创建一个定时任务。

/*
 * 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 hello;

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()));
    }
}

The Scheduled annotation defines when a particular method runs. NOTE: This example uses fixedRate, which specifies the interval between method invocations measured from the start time of each invocation. There are other options, like fixedDelay, which specifies the interval between invocations measured from the completion of the task. You can also use @Scheduled(cron=". . .") expressions for more sophisticated task scheduling.
这个Scheduled注解声明在特定的启动方法上。注意:本例使用fixedRate,它指定从每次调用的开始时间开始测量的方法调用之间的间隔。
还有其他的选择,比如fixedDelay,它指定从任务完成开始测量的调用间隔。你也能使用@Scheduled(cron="…")表达式生成更多复杂的定时任务。

Enable Scheduling(启动调度)

Although scheduled tasks can be embedded in web apps and WAR files, the simpler approach demonstrated below creates a standalone application. You package everything in a single, executable JAR file, driven by a good old Java main() method.
尽管定时任务能够被嵌入web apps和WAR文件中,但是下面演示了一个更简单的方法创建的一个独立程序。你可以打包所有东西在一个简单的、可执行的JAR文件中,该文件由老的main方法启动。

package hello;

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

@SpringBootApplication
@EnableScheduling
public class Application {

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

@SpringBootApplication is a convenience annotation that adds all of the following:
@SpringBootApplication是一个方便的注解,它包含了以下所有内容:

  • @Configuration: Tags the class as a source of bean definitions for the application context.将类标记为应用上下文bean定义的来源。
  • @EnableAutoConfiguration: Tells Spring Boot to start adding beans based on classpath settings, other beans, and various property settings. For example, if spring-webmvc is on the classpath, this annotation flags the application as a web application and activates key behaviors, such as setting up a DispatcherServlet.告诉SpringBoot开始添加类路径下的bean和各种各样的属性设置。
  • @ComponentScan: Tells Spring to look for other components, configurations, and services in the hello package, letting it find the controllers.告诉Spring去查看在这个hello包下其他的组件、配置和服务,让他找到controllers。

The main() method uses Spring Boot’s SpringApplication.run() method to launch an application. Did you notice that there was not a single line of XML? There is no web.xml file, either. This web application is 100% pure Java and you did not have to deal with configuring any plumbing or infrastructure.
main()方法使用SpringBoot的SpringApplication.run()方法来启动应用程序。你注意到了它没有一行XML代码吗?也没有web.xml文件。这个web应用程序是100%纯Java的,你不需要配置任何plumbing或者infrastructure。

@EnableScheduling ensures that a background task executor is created. Without it, nothing gets scheduled.
@EnableScheduling 注解确保创建了后台任务执行器。没有它,什么事情都无法被调度。

Build an executable JAR(构建一个可执行JAR)

You can run the application from the command line with Gradle or Maven. You can also build a single executable JAR file that contains all the necessary dependencies, classes, and resources and run that. Building an executable jar so makes it easy to ship, version, and deploy the service as an application throughout the development lifecycle, across different environments, and so forth.
你可以使用Gradle或Maven从命令行运行应用程序。你还可以构建一个包含所有必要的依赖项、类和资源的可执行JAR文件并运行它。构建一个可执行jar,以便在整个开发生命周期、不同的环境等中将服务作为应用程序进行交付、版本化和部署。

If you use Gradle, you can run the application by using ./gradlew bootRun. Alternatively, you can build the JAR file by using ./gradlew build and then run the JAR file, as follows:
如果你使用Gradle,你可以使用 ./gradlew bootRun的方式运行应用。或者,你可以使用./gradlew build构建JAR文件,然后运行JAR文件,如下所示:

java -jar build/libs/gs-messaging-rabbitmq-0.1.0.jar

If you use Maven, you can run the application by using ./mvnw spring-boot:run. Alternatively, you can build the JAR file with ./mvnw clean package and then run the JAR file, as follows:
如果你使用Maven,你可以使用./mvnw spring-boot:run运行应用程序。或者,你可以使用./mvnw clean包构建JAR文件,然后运行JAR文件,如下所示:

java -jar target/gs-messaging-rabbitmq-0.1.0.jar

The steps described here create a runnable JAR. You can also build a classic WAR file.
这里描述的步骤是创建一个可运行的JAR。当然,你也可以构建一个经典的WAR文件。

Logging output is displayed and you can see from the logs that it is on a background thread. You should see your scheduled task fire every 5 seconds:

[...]
2016-08-25 13:10:00.143  INFO 31565 --- [pool-1-thread-1] hello.ScheduledTasks : The time is now 13:10:00
2016-08-25 13:10:05.143  INFO 31565 --- [pool-1-thread-1] hello.ScheduledTasks : The time is now 13:10:05
2016-08-25 13:10:10.143  INFO 31565 --- [pool-1-thread-1] hello.ScheduledTasks : The time is now 13:10:10
2016-08-25 13:10:15.143  INFO 31565 --- [pool-1-thread-1] hello.ScheduledTasks : The time is now 13:10:15

Summary

Congratulations! You created an application with a scheduled task. Heck, the actual code was shorter than the build file! This technique works in any type of application.
恭喜!你创建了一个定时任务。见鬼,实际的代码比创建的文件要短!这个技术适用于任何类型的程序。

译者笔记

  • particular:adj. 特别的;详细的;独有的;挑剔的,n. 详细说明;个别项目
  • interval:n. 间隔;间距;幕间休息
  • sophisticated:adj. 复杂的;精致的;久经世故的;富有经验的
  • embedded:adj. 嵌入式的;植入的;内含的
  • standalone:adj. (计算机)独立运行的;(公司)独立的
  • ensures that:确保

你可能感兴趣的:(每周一篇技术翻译文章)