新知识点,@Scheduled,
作用:可以通过@Scheduled配置定时任务。
1 package com.example.demo.scheduled; 2 3 import java.time.LocalDateTime; 4 import java.time.format.DateTimeFormatter; 5 6 import org.springframework.scheduling.annotation.EnableScheduling; 7 import org.springframework.scheduling.annotation.Scheduled; 8 import org.springframework.stereotype.Component; 9 10 @Component 11 @EnableScheduling 12 public class scheduleTask { 13 14 private DateTimeFormatter ofPattern; 15 16 @Scheduled(cron = "0/5 * * * * ?") 17 public void task() { 18 LocalDateTime now = LocalDateTime.now(); 19 ofPattern = DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm:ss"); 20 System.out.println(now.format(ofPattern)+"it is task"); 21 } 22 }
展示的结果:
备注:
@Component,把类注入spring的上下文。
@EnableScheduling,开启定时任务
@Scheduled,配置需要定时执行的任务,除了支持灵活的参数表达式cron之外,还支持简单的延时操作,例如 fixedDelay ,fixedRate 填写相应的毫秒数即可。
其中cron参数详细信息如下:
Cron表达式参数分别表示:
- 秒(0~59) 例如0/5表示每5秒
- 分(0~59)
- 时(0~23)
- 日(0~31)的某天,需计算
- 月(0~11)
- 周几( 可填1-7 或 SUN/MON/TUE/WED/THU/FRI/SAT)
备注:有一些网站,写着定时任务,可以写七个参数,最后一个参数,与年份相关。
查看 https://blog.csdn.net/fly910905/article/details/79566020 后,明白了 spring 3.0 后只支持 “6个参数”的cron