需要定时器的地方好像还挺多. 之前项目中有用到使用定时器循环订单时间,然后将超时的订单状态更改. springboot的@Scheduled注解能够很快速完成我们需要的定时任务. @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这两个参数开始计时的时间不一样.如果需要调用的方法执行时间比较长, 这时差别就能体现出来. fixedRate:上一次开始执行时间点后再次执行; fixedDelay:上一次执行完毕时间点后再次执行; 还发现还有一种方法是调用配置文件的方法. @Scheduled(fixedDelayString = "${jobs.fixedDelay}") public void getTask1() { System.out.println("任务1,从配置文件加载任务信息,当前时间:" + dateFormat.format(new Date())); } 有兴趣的可以具体看下http://blog.csdn.net/je_ge/article/details/53434227. 附上一个在线Cron表达式生成器
|
|
来自: WindySky > 《sping架构体系》