springboot的@Scheduled注解可以很快速完成咱们须要的定时任务.spring
代码以下:springboot
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这两个参数开始计时的时间不同.若是须要调用的方法执行时间比较长, 这时差异就能体现出来.app
fixedRate:上一次开始执行时间点后再次执行;spa
fixedDelay:上一次执行完毕时间点后再次执行;.net
还能够将执行执行频率、cron表达式放到application.properties中 调用以下code
@Scheduled(fixedDelayString = "${jobs.fixedDelay}") public void getTask1() { System.out.println("任务1,从配置文件加载任务信息,当前时间:" + dateFormat.format(new Date())); }
经常使用Cron表达式orm
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表达式在线生成器blog