Spring Boot实战-定时任务
内容参考:《Spring Boot企业级项目开发——入门到精通》 钟林森,罗剑 著
什么是定时任务?
定时任务:表示根据设定的某个时间频率,重复不断地被执行的某个任务。应用场景:定时获取一个数据库中的数据,并同步到其他数据库中;“定时查询即将过期失效的订单,并对其做失效处理”
核心步骤
1.写一个@Component 注解的类,使用@Scheduled(cron=“cron表达式”)注解的方法。如@Scheduled(cron = “0/5 * * * * ?”)
2. Spring Boot启动程序上,添加@EnableScheduled:“开启定时任务调度”
Spring Boot实现-定时任务
1.新建项目 spring-boot-scheduled
2.pom文件如下,引入spring-boot-starter-web 2.3.5.RELEASE,完整的pom.xml如下:
<?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>com.dreamli</groupId>
<artifactId>spring-boot-scheduled</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<name>spring-boot-scheduled Maven Webapp</name>
<!-- FIXME change it to the project's website -->
<url>http://www.example.com</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>2.3.5.RELEASE</version>
</dependency>
</dependencies>
</project>
3.核心配置文件 application.yml
server:
port: 9090
servlet:
context-path: /schedule-task
4.启动类
package com.dreamli;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;
/**
* @Title Application.class
* @Package com.dreamli
* @Description 启动类
* @Author zhaoml
* @DateTime 2023/3/8 16:38
* @Version V1.0
*/
@SpringBootApplication
//开启定时任务调度
@EnableScheduling
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class,args);
}
}
5.定时任务类
package com.dreamli.scheduleTask;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
/**
* @Title ScheduledDemo.class
* @Package com.dreamli.scheduleTask
* @Description 简单单线程定时任务
* @Author zhaoml
* @DateTime 2023/3/8 16:42
* @Version V1.0
*/
@Component
public class ScheduledDemo {
// cron表达式的含义:从0秒开始,每5秒,控制台输出一次
// 在线cron 表达式生成器,https://cron.qqe2.com/
@Scheduled(cron = "0/5 * * * * ?")
public void simpleSingleThreadScheduledTask(){
System.out.println(System.currentTimeMillis()+"每5秒,执行一次的定时任务");
}
}
- 启动项目,观察控制台打印信息,如下。到此,可以看出,定时任务已经执行了。