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

2023-08-30  本文已影响0人  CoderInsight

(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),以分钟为例整理定时任务的规则

# 执行结果日志
当前为第1次调用,且调用时间为2023-08-31 10:20:00.029
当前为第2次调用,且调用时间为2023-08-31 10:21:00.016
当前为第3次调用,且调用时间为2023-08-31 10:22:00.010
# 执行结果日志
当前为第1次调用,且调用时间为2023-08-31 10:20:02.029
当前为第2次调用,且调用时间为2023-08-31 10:21:02.016
当前为第3次调用,且调用时间为2023-08-31 10:22:02.010
# 执行结果日志
当前为第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表达式

上一篇 下一篇

猜你喜欢

热点阅读