SpringBoot学习笔记(12):计划任务
快速开始
本指南将指导您完成使用Spring安排任务的步骤。
参考教程:
https://spring.io/guides/gs/scheduling-tasks/
https://docs.spring.io/spring/docs/current/spring-framework-reference/integration.html#scheduling
使用Maven进行构建
首先,设置一个基本的构建脚本。在使用Spring构建应用程序时,您可以使用任何您喜欢的构建系统,但此处包含了使用Maven所需的代码。如果您不熟悉Maven,请参阅使用Maven构建Java项目。
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>org.springframework</groupId> <artifactId>gs-scheduling-tasks</artifactId> <version>0.1.0</version> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.0.3.RELEASE</version> </parent> <properties> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project>
创建一个计划任务
import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; import java.text.SimpleDateFormat; import java.util.Date; @Component public class ScheduledTasks { private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss"); @Scheduled(fixedRate = 1000) public void reportCurrentTime() { System.out.println(dateFormat.format(new Date())); } }
@Schedule注释定义特定方法何时运行。注意:此示例使用fixedRate,它指定从每次调用的开始时间开始测量的方法调用之间的间隔。还有其他选项,例如fixedDelay,它指定从完成任务开始测量的调用之间的间隔。您还可以使用@Scheduled(cron =“...”)表达式进行更复杂的任务调度。
如果您需要更为复杂的时间调度,请参考:
https://docs.spring.io/spring/docs/current/spring-framework-reference/integration.html#scheduling-annotation-support-scheduled
https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/scheduling/support/CronSequenceGenerator.html
http://www.manpagez.com/man/5/crontab/
"0 0 * * * *" = the top of every hour of every day. "*/10 * * * * *" = every ten seconds. "0 0 8-10 * * *" = 8, 9 and 10 o'clock of every day. "0 0 6,19 * * *" = 6:00 AM and 7:00 PM every day. "0 0/30 8-10 * * *" = 8:00, 8:30, 9:00, 9:30, 10:00 and 10:30 every day. "0 0 9-17 * * MON-FRI" = on the hour nine-to-five weekdays "0 0 0 25 12 ?" = every Christmas Day at midnight
启用计划
@EnableScheduling确保创建后台任务执行程序。没有它,没有任何安排。
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) throws Exception { SpringApplication.run(Application.class); } }
测试
在控制台按照规定间隔打印当前时间