栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

SpringBoot整合定时任务

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

SpringBoot整合定时任务

整合定时任务
  • 使用@Scheduled创建定时任务
    • @EnableScheduling注解
    • @Scheduled注解
      • cron
      • fixedRate
      • fixedDelay
      • initialDelay

使用@Scheduled创建定时任务

在Spring Boot的主类中加入@EnableScheduling注解,启用定时任务的配置.
先创建一个定时类

@Component
@Slf4j
public class ScheduledTasks {
    
@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同理。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/606040.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号