本指南将指导你完成使用Spring调度任务的步骤。html
你将构建一个应用程序,使用Spring的@Scheduled
注解每五秒打印一次当前时间。java
你还能够将代码直接导入IDE:git
请执行如下操做:github
git clone https://github.com/spring-guides/gs-scheduling-tasks.git
gs-scheduling-tasks/initial
完成后,你能够根据gs-scheduling-tasks/complete
中的代码检查结果。spring
如今你已经设置了项目,能够建立调度任务。apache
src/main/java/hello/ScheduledTasks.java
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())); } }
Scheduled
注解定义特定方法什么时候运行,注意:此示例使用fixedRate
,它指定从每次调用的开始时间计算的方法调用之间的间隔。还有其余选项,例如fixedDelay
,它指定从完成任务计算的调用之间的间隔,你还能够使用@Scheduled(cron=". . .")
表达式进行更复杂的任务调度。segmentfault
虽然调度任务能够嵌入到Web应用程序和WAR文件中,但下面演示的更简单的方法建立了一个独立的应用程序,将全部内容打包在一个可执行的JAR文件中,由main()
方法驱动。api
src/main/java/hello/Application.java
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
是一个方便的注解,添加了如下全部内容:mvc
@Configuration
将类标记为应用程序上下文的bean定义源。@EnableAutoConfiguration
告诉Spring Boot根据类路径设置、其余bean和各类属性设置开始添加bean。@EnableWebMvc
,但Spring Boot会在类路径上看到spring-webmvc时自动添加它,这会将应用程序标记为Web应用程序并激活关键行为,例如设置DispatcherServlet
。@ComponentScan
告诉Spring在hello
包中查找其余组件、配置和服务,容许它找到控制器。main()
方法使用Spring Boot的SpringApplication.run()
方法来启动应用程序,你是否注意到没有一行XML?也没有web.xml文件,此Web应用程序是100%纯Java,你无需处理配置任何管道或基础结构。
@EnableScheduling
确保建立后台任务执行程序,没有它,就没有任何调度。
你能够使用Gradle或Maven从命令行运行该应用程序,或者,你能够构建一个包含全部必需依赖项、类和资源的可执行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文件。
显示日志输出,你能够从日志中看到它在后台线程上,你应该看到你的调度任务每5秒出发一次:
[...] 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