使用@Scheduled创建定时任务
在Spring Boot的主类中加入@EnableScheduling注解,启用定时任务的配置.
先创建一个定时类
@Component
@Slf4j
public class ScheduledTasks {
/*
每隔3s时间执行到taskService
*/
@Scheduled(fixedRate = 3000)
public void taskService(){
//System.currentTimeMillis()是获取当前系统的时间。
log.info("<定数任务执行>"+System.currentTimeMillis());
}
在启动类加上@EnableScheduling注解
可以看到结果
@EnableScheduling注解
@EnableScheduling来开启对计划任务的支持
@Scheduled注解
@Scheduled注解是spring boot提供的用于定时任务控制的注解,主要用于控制任务在某个指定时间执行,或者每隔一段时间执行.注意需要配合@EnableScheduling使用,配置@Scheduled主要有三种配置执行时间的方式,cron,fixedRate,fixedDelay.
cron
cron是@Scheduled的一个参数,是一个字符串,以5个空格隔开,只允许6个域(注意不是7个,7个直接会报错),分别表示秒,分,时,日,月,周.
示例
@Scheduled(cron = "0 * * * 1 SAT") //每年的1月的所有周六的所有0秒时间执行
@Scheduled(cron = "0 0 0 1 Jan ?") //每年的1月的1日的0时0分0秒执行
cron支持占位符,若在配置文件中有
cron = 2 2 2 2 2 ?
则
@Scheduled(cron = “${cron}”)
表示每年的二月二号的两时两分两秒执行.
cron 在线生成器,挺好用的,不用记这些规则。
https://www.bejson.com/othertools/cron/
fixedRate
fixedRate表示自上一次执行时间之后多长时间执行,以ms为单位. 如
@Scheduled(fixedRate = 5000)
意思就是5秒运行一次。
fixedRateString
有一个类似的参数叫fixedRateString,是字符串的形式,支持占位符. 和fixedRate差不多
@Scheduled(fixedRateString = "1000")
自上次执行1秒再执行.
若在配置文件中有相应的属性,可以用占位符获取属性,如在application.properties中有
interval=2000。
这个表示两秒间隔
@Scheduled(fixedRateStirng="${interval}")
fixedDelay
fixedDelay与fixedRate有点类似,不过fixedRate是上一次开始之后计时,fixedDelay是上一次结束之后计时,也就是说,fixedDelay表示上一次执行完毕之后多长时间执行,单位也是ms.
@Scheduled(fixedDelay = 1000 * 3600 * 12) //上一次执行完毕后半天后再次执行
fixedDelayString和上面fixedRateString同理。
initialDelay
initialDelay表示首次延迟多长时间后执行,单位ms,之后按照cron/fixedRate/fixedRateString/fixedDelay/fixedDelayString指定的规则执行,需要指定其中一个规则.
@Scheduled(initialDelay=1000,fixedRate=1000) //首次运行延迟1s
initialDelayString和上面fixedRateString同理。