• springboot定时任务 @Scheduled


     springboot的@Scheduled注解能够很快速完成我们需要的定时任务.

     代码如下:

    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.scheduling.annotation.EnableScheduling;
    import org.springframework.scheduling.annotation.Scheduled;
    import org.springframework.stereotype.Component;
    
    
    @Configuration
    @Component
    @EnableScheduling
    public class UserTypeUpdateJob  {
        
             SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
             
            /*每100秒执行一次*/
            @Scheduled(fixedRate = 100000)
            public void timerRate() {
                System.out.println("我是:timerRate");
            }
            
            /*第一次10秒后执行,当执行完后2秒再执行*/
            @Scheduled(initialDelay = 10000, fixedDelay = 2000)
            public void timerInit() {
                System.out.println("init : "+dateFormat.format(new Date()));
            }
    
            /*每天15:39:00时执行*/
            @Scheduled(cron = "0 39 15 * * ? ")
            public void timerCron() {
                System.out.println("current time : "+ dateFormat.format(new Date()));
            }
    }

    其中需要注意的是:fixedRate和fixedDelay这两个参数开始计时的时间不一样.如果需要调用的方法执行时间比较长, 这时差别就能体现出来.

    fixedRate:上一次开始执行时间点后再次执行;

    fixedDelay:上一次执行完毕时间点后再次执行;

    还可以将执行执行频率、cron表达式放到application.properties中 调用如下

    @Scheduled(fixedDelayString = "${jobs.fixedDelay}")
      public void getTask1() {
        System.out.println("任务1,从配置文件加载任务信息,当前时间:" + dateFormat.format(new Date()));
      }

    常用Cron表达式

    0 10,14,16 * * ? 每天上午10点,下午2点,4点 
    0/30 9-17 * * ?   朝九晚五工作时间内每半小时 
    0 12 ? * WED 表示每个星期三中午12点 
    "0 0 12 * * ?" 每天中午12点触发 
    "0 * 14 * * ?" 在每天下午2点到下午2:59期间的每1分钟触发 
    "0 0/5 14 * * ?" 在每天下午2点到下午2:55期间的每5分钟触发 
    "0 0/5 14,18 * * ?" 在每天下午2点到2:55期间和下午6点到6:55期间的每5分钟触发 
    "0 0-5 14 * * ?" 在每天下午2点到下午2:05期间的每1分钟触发 
    "0 10,44 14 ? 3 WED" 每年三月的星期三的下午2:10和2:44触发 
    "0 15 10 ? * MON-FRI" 周一至周五的上午10:15触发 
    "0 15 10 15 * ?" 每月15日上午10:15触发 
    "0 15 10 L * ?" 每月最后一日的上午10:15触发 
    "0 15 10 ? * 6L" 每月的最后一个星期五上午10:15触发 
    "0 15 10 ? * 6L 2002-2005" 2002年至2005年的每月的最后一个星期五上午10:15触发 
    "0 15 10 ? * 6#3" 每月的第三个星期五上午10:15触发 
    "0 15 10 ? * *" 每天上午10:15触发 
    "0 15 10 * * ?" 每天上午10:15触发 
    "0 15 10 * * ? *" 每天上午10:15触发 
    "0 15 10 * * ? 2005" 2005年的每天上午10:15触发

    Cron表达式在线生成器

    http://cron.qqe2.com/

    http://www.pppet.net/

  • 相关阅读:
    【JZOJ6223】【20190617】互膜
    【JZOJ6225】【20190618】计数
    【JZOJ6226】【20190618】纳什均衡
    【JZOJ6210】【20190612】wsm
    【学习笔记】析合树
    【JZOJ6206】【20190610】二分图边染色
    【loj3123】【CTS2019】重复
    【loj3120】【CTS2019】珍珠
    【loj3119】【CTS2019】随机立方体
    CTS&&APIO2019爆零记
  • 原文地址:https://www.cnblogs.com/weitaming/p/8359678.html
Copyright © 2020-2023  润新知