这篇博文将说明,如何一步一步完成Spring的任务调度功能。
主要是使用@Scheduled注解,完成每5秒打印当前时间。
首先在Maven中增加awaitility依赖包
- <dependency>
- <groupId>org.awaitilitygroupId>
- <artifactId>awaitilityartifactId>
- <version>3.1.2version>
- <scope>testscope>
- dependency>
整体Maven如下:
- "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.0modelVersion>
-
- <groupId>org.examplegroupId>
- <artifactId>SchedulingTasksartifactId>
- <version>1.0-SNAPSHOTversion>
-
- <dependencies>
-
- <dependency>
- <groupId>org.springframework.bootgroupId>
- <artifactId>spring-boot-starter-webartifactId>
- <version>2.1.10.RELEASEversion>
- dependency>
-
- <dependency>
- <groupId>org.awaitilitygroupId>
- <artifactId>awaitilityartifactId>
- <version>3.1.2version>
- <scope>testscope>
- dependency>
-
- dependencies>
-
- project>
创建调度调度任务的类,ScheduleTasks.java
- package cn.it1995.component;
-
- import org.slf4j.Logger;
- import org.slf4j.LoggerFactory;
- 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 Logger log = LoggerFactory.getLogger(ScheduledTasks.class);
-
- private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
-
- @Scheduled(fixedDelay = 5000)
- public void reportCurrentTime(){
-
- log.info("The time is now {}", dateFormat.format(new Date()));
- }
- }
@Scheduled注解说明了在合适调用,比如fixedDelay说明每多少毫秒调用一次。这里还有其他选项,比如使用corn,这里全称应该是crontab,也就是定时任务,如@Scheduled(cron="...")
- package cn.it1995;
-
- import org.springframework.boot.SpringApplication;
- import org.springframework.boot.autoconfigure.SpringBootApplication;
- import org.springframework.scheduling.annotation.EnableScheduling;
-
- @SpringBootApplication
- @EnableScheduling
- public class Main {
-
- public static void main(String[] args){
-
- SpringApplication.run(Main.class, args);
- }
- }
最后在@SpringBootApplication注解的地方,也就是main方法的地方,加上@EnableScheduling注解,这个注解的作用是使得后台任务调用执行被创建。
代码如下:Main.java
- package cn.it1995;
-
- import org.springframework.boot.SpringApplication;
- import org.springframework.boot.autoconfigure.SpringBootApplication;
- import org.springframework.scheduling.annotation.EnableScheduling;
-
- @SpringBootApplication
- @EnableScheduling
- public class Main {
-
- public static void main(String[] args){
-
- SpringApplication.run(Main.class, args);
- }
- }
运行截图如下:
代码打包如下:
Java/SchedulingTasks at master · fengfanchen/Java · GitHub