0%

SpringBoot-定时任务

前言

SpringBoot默认已经帮我们实行了,只需要添加相应的注解就可以实现。

SpringBoot整合定时任务其实就两点:
1.创建一个能被定时任务类,方法上加入@Scheduled注解
2.在启动类application上加入@EnableScheduling注解

pom文件

只需要引入 Spring Boot Starter 包即可

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
<?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>

application类启用定时

在启动类上面加上@EnableScheduling即可开启定时

1
2
3
4
5
6
7
8
@SpringBootApplication
@EnableScheduling
public class SpringbootScheduledApplication {

public static void main(String[] args) {
SpringApplication.run(SpringbootScheduledApplication.class, args);
}
}

创建定时任务类TestTimer

  1. @Component注解表明一个类会作为组件类,并告知Spring要为这个类创建bean。
  2. @Scheduled开启定时
    1
    2
    3
    4
    5
    6
    7
    8
    @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/

欢迎关注我的其它发布渠道