This guide walks you through the steps for scheduling tasks with Spring.
这篇指南将会向你介绍Spring定时任务。
You’ll build an application that prints out the current time every five seconds using Spring’s @Scheduled annotation.
你将会使用Spring的@Scheduled注解构建一个每五分钟输出当前时间的应用。
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开始指南,你可以从零开始完成每一步或者跳过那些你熟悉的步骤。无论如何,你都能够完成这份代码。
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="…")表达式生成更多复杂的定时任务。
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是一个方便的注解,它包含了以下所有内容:
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 注解确保创建了后台任务执行器。没有它,什么事情都无法被调度。
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
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.
恭喜!你创建了一个定时任务。见鬼,实际的代码比创建的文件要短!这个技术适用于任何类型的程序。