springboot 定时任务@Scheduled注解

须要定时器的地方好像还挺多. 以前项目中有用到使用定时器循环订单时间,而后将超时的订单状态更改.spring

springboot的@Scheduled注解可以很快速完成咱们须要的定时任务.springboot

@Component
public class ExampleTimer {
     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这两个参数开始计时的时间不同.若是须要调用的方法执行时间比较长, 这时差异就能体现出来.spa

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

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

还发现还有一种方法是调用配置文件的方法.orm

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

有兴趣的能够具体看下http://blog.csdn.net/je_ge/article/details/53434227.blog

附上一个在线Cron表达式生成器get

http://cron.qqe2.com/it

相关文章
相关标签/搜索