简介
Spring Task是Spring框架提供的任务调度工具,可以定时执行任务,只要是需要定时处理的场景都可以使用Spring Task
cron表达式
Cron 表达式由 6~7 个字段组成,分别表示不同的时间单位:
秒 分 时 日 月 星期 [年],其中年是可选的
上图来自以下网站
在线生成cron表达式
使用
导入坐标
maven坐标spring-context,在spring-boot-starter中
在启动类添加注解
通过 @EnableScheduling 注解开启定时任务支持
@SpringBootApplication
@EnableScheduling // 启用定时任务
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
自定义定时任务类
注意需要添加@Component注解,将定时任务类实例化并交给ioc容器管理
@Component
public class MyTask {
@Scheduled(fixedRate = 5000) // 每5秒执行一次(上次开始后计算)
public void task1() {
System.out.println("Fixed Rate Task: " + new Date());
}
@Scheduled(fixedDelay = 3000) // 上次任务结束后,延迟3秒执行
public void task2() {
// 模拟耗时操作
Thread.sleep(1000);
}
@Scheduled(cron = "0 0/5 9-18 * * ?") // 每天9点到18点,每5分钟执行
public void task3() {
System.out.println("Cron Task: " + new Date());
}
}