SpringBoot定時任務

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:確保
發佈了72 篇原創文章 · 獲贊 300 · 訪問量 2萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章