前言
SpringBoot默认已经帮我们实行了,只需要添加相应的注解就可以实现。
SpringBoot整合定时任务其实就两点:
1.创建一个能被定时任务类,方法上加入@Scheduled注解
2.在启动类application上加入@EnableScheduling注解
1、pom文件
只需要引入 Spring Boot Starter 包即可
<?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>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.6.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.huzh</groupId>
<artifactId>springboot-scheduled</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>springboot-scheduled</name>
<description>springboot-scheduled</description>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!-- 调试热启动 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
2、application类启用定时
在启动类上面加上@EnableScheduling即可开启定时
@SpringBootApplication
@EnableScheduling
public class SpringbootScheduledApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootScheduledApplication.class, args);
}
}
3、创建定时任务类TestTimer
1.@Component注解表明一个类会作为组件类,并告知Spring要为这个类创建bean。
2.@EnableScheduling开启定时
@Component
public class TestTimer {
@Scheduled(cron = "0/1 * * * * ?")
private void test() {
System.out.println("执行定时任务的时间是" + new Date());
}
}
备注:
需要注意的是@Scheduled(cron = “0/1 * * * * ?”)中cron的值根据自己实际需要去写,可参考http://cron.qqe2.com/
网友评论