美文网首页
@Scheduled.cron表达式在Springboot中的应

@Scheduled.cron表达式在Springboot中的应

作者: CoderInsight | 来源:发表于2023-08-30 10:28 被阅读0次

(1),Schedule.cron表达式

Cron表达式是一个字符串,在Springboot中需要配合 @Scheduled(cron = "") 一起使用,同时如果想 @Schedule 注解生效,那么也需要在main方法所在的启动类中添加 @EnableScheduling 注解,开启定时任务。

@Component  
public class DemoSchedule {  
  
    private final AtomicInteger atomicInteger = new AtomicInteger(0);  
  
    private final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");  
  
    @Scheduled(cron = "0 */1 * * * ?")  
    public void demo(){  
        int i = atomicInteger.incrementAndGet();  
        
        System.out.println("当前为第" + i + "次调用,且调用时间为" + dateFormat.format(new Date()));  
    }  
}

1),以分钟为例整理定时任务的规则

  • @Scheduled(cron = "0 */1 * * * ?") --> 每1分钟执行一次,且执行时间是每1分钟的0秒;
# 执行结果日志
当前为第1次调用,且调用时间为2023-08-31 10:20:00.029
当前为第2次调用,且调用时间为2023-08-31 10:21:00.016
当前为第3次调用,且调用时间为2023-08-31 10:22:00.010
  • @Scheduled(cron = "2 */1 * * * ?") --> 每1分钟执行一次,且执行时间是每1分钟的2秒;
# 执行结果日志
当前为第1次调用,且调用时间为2023-08-31 10:20:02.029
当前为第2次调用,且调用时间为2023-08-31 10:21:02.016
当前为第3次调用,且调用时间为2023-08-31 10:22:02.010
  • @Scheduled(cron = "2 0/1 * * * ?") --> 每1分钟执行一次,且执行时间是每1分钟的2秒,分子位置的数字无论是0还是其他的“0~59”之间的数据都不会改变定时任务执行的结果,且与 @Scheduled(cron = "2 */1 * * * ?") 等价;
# 执行结果日志
当前为第1次调用,且调用时间为2023-08-31 10:20:02.029
当前为第2次调用,且调用时间为2023-08-31 10:21:02.016
当前为第3次调用,且调用时间为2023-08-31 10:22:02.010

2),其他维度的使用、以及常见用法示例

参考连接-@Schedule cron表达式

  • 每天凌晨1点执行一次:0 0 1 * * ?
  • 每月1号凌晨1点执行一次:0 0 1 1 * ?
  • 每月最后一天23点执行一次:0 0 23 L * ?
  • 每周星期天凌晨1点实行一次:0 0 1 ? * L

相关文章

网友评论

      本文标题:@Scheduled.cron表达式在Springboot中的应

      本文链接:https://www.haomeiwen.com/subject/dlaomdtx.html