SpringBoot定时任务 @Scheduled注解(五)
首先在启动类上加上 @EnableScheduling 注解开启定时任务。
package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;
@SpringBootApplication
@EnableScheduling
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
然后在Service 中写一个hello()方法来测试,并在方法上标注 @Scheduled 注解,然后给注解的cron属性赋上指定值。
package com.example.demo.service;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
@Service
public class TestService {
/**
* 从左到右六个 * 号。
* 依次表示秒、分、时、日、月、星期。
*/
@Scheduled(cron = "* * * * * *")//当前表示任意星期、任意月、任意日、任意时、任意分、任意秒都执行hello()方法。
public void hello(){
System.err.println("HelloWorld。。。");
}
}
运行项目,看控制台,执行结果:
可以发现当前其实就是每一秒都执行 hello() 方法。
既然如此,关键就是 cron 属性表达式的写法。cron表达式的写法:
字段 | 允许值 |
---|---|
秒 | 0-59 |
分 | 0-59 |
时 | 0-23 |
日 | 1-31 |
月 | 1-12 |
星期 | 0-7或SUN-SAT ,0和7都是星期日 |
特殊字符 | 代表含义 |
---|---|
, | 枚举 |
- | 区间 |
* | 任意 |
/ | 步长 |
? | 日/星期冲突匹配 |
L | 最后 |
W | 工作日 |
# | 星期,5#3表示第3个星期五 |
常用示例:
//每分钟的第零秒、第一秒、第二秒执行一次
@Scheduled(cron = "0,1,2 * * * * *")
//表示在每月的1日的凌晨2点调整任务
@Scheduled(cron = "0 0 2 1 * ? *")
//每天中午12点触发
@Scheduled(cron = "0 0 12 * * ?")
//表示每个星期三中午12点
@Scheduled(cron = "0 0 12 ? * WED")
//2020年的每天上午10:00触发
@Scheduled(cron = "0 0 10 * * ? 2020")
//周一至周五的上午10:15触发
@Scheduled(cron = "0 15 10 ? * MON-FRI")