开启定时任务
1 2 3 4 5 6 7 8
| @EnableScheduling @SpringBootApplication public class MyApplication {
public static void main(String[] args) { SpringApplication.run(MyApplication.class, args); } }
|
配置(非必须)
1 2 3 4 5 6 7 8
| spring: task: scheduling: thread-name-prefix: spring-scheduling- pool: size: 1
|
测试
1 2 3 4 5 6 7 8 9 10
| @Component public class TestScheduling {
private static final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
@Scheduled(fixedDelay = 3000) public void printDate(){ System.out.println(sdf.format(new Date())); } }
|
启动程序控制台:
2024-10-22 22:52:14
2024-10-22 22:52:17
2024-10-22 22:52:20
注解
@Scheduled(fixedRate = 3000) :上一次开始执行时间点之后3秒再执行
@Scheduled(fixedDelay = 3000) :上一次执行完毕时间点之后3秒再执行
@Scheduled(initialDelay=1000, fixedRate=3000) :第一次延迟1秒后执行,之后按fixedRate的规则每3秒执行一次
@Scheduled(cron=”*/3 * * * * ?”) :通过cron表达式定义规则