spring定时任务调度

本文将告诉你如何使用spring的任务调度。主要使用@Scheduled注解

需要会使用maven

第一步 pom.xml配置

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
<?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.xxz</groupId>
<artifactId>scheduled-task-test</artifactId>
<version>1.0</version>

<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.0.RELEASE</version>
</parent>

<properties>
<java.version>1.8</java.version>
</properties>

<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
</dependencies>

<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>

</project>

第二步 定时任务类(ScheduledTasks)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
package org.xxz.task;

import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Component
public class ScheduledTasks {

@Scheduled(fixedRate = 5000)
public void now() {
log.info("The time is now {}", new Date());
}
}

@Scheduled有三种类型参数fixedRate, fixedDelay, cron

fixedRate 表示每隔多少毫秒执行一次

fixedDelay 表示任务执行完成后隔多少毫秒执行一次

cron 定时任务表达式

第三步 启动类(Application)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
package org.xxz;

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);
}
}

第四步 打包运行

1
2
3
cd scheduled-task-test
mvn clean package
java -jar target/scheduled-task-test-1.0.jar

扩展知识:如果不想使用spring的任务调度,可以使用jdk自带的任务调度类

ScheduledExecutorService#schedule

ScheduledExecutorService#scheduleAtFixedRate

ScheduledExecutorService#scheduleWithFixedDelay

今天的分享就到这里了。谢谢阅读。