1.什么是定时器?
在指定的时间,执行相应的业务代码。
2.为什么使用定时器?
比如: OSS文件系统服务器,会产生大量冗余文件。定时删除冗余文件【凌晨2~3点】。
比如: 下单后半个未支付--取消订单
(1)导入定时器依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-quartz</artifactId>
</dependency>
(2)编写定义任务代码
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
/**
* @program: qy151-springboot
* @description:
* @create: 2022-07-25 14:20
**/
@Component //该类交于spring容器来管理
public class QuartzTask {
//任务代码cron:定义定时任务的规则 https://www.pppet.net/
@Scheduled(cron = "0/1 * * * * ?")
public void task01(){
System.out.println("业务代码");
}
}
(3) 开启定时任务的注解
(4)测试
package com.xzh.config;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
@Component//该类交于spring容器来管理
public class QuartzTest {
@Scheduled(cron = "0/1 * * * * ? ") //定时器注解 任务代码cron 规则网址https://www.pppet.net/
public void Test01(){
System.out.println("执行定时器任务代码段");
}