Spring Schedule是Spring提供的定时任务框架,相较于Quartz,Schedule更加简单易用,在中小型应用中,对于大部分需求,Schedule均可以胜任。java
在SpringBoot使用Spring Schedule很是简单,由于SpringBoot自身的starter中已经集成了Schedule,而不须要咱们作更多的处理。服务器
使用@EnableScheduling注解开启定时功能,该注解可使用在启动类上,也能够注解于定时任务的类上。而后使用@Scheduled注解配合其参数完成定时任务。框架
例如咱们须要每一秒执行一次的任务, 写成@Scheduled(fixedRate = 1000)便可。3d
@EnableScheduling @Component public class Task { private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss"); @Scheduled(fixedRate = 1000) public void taskOne(){ System.out.println("如今时间:" + dateFormat.format(new Date())); } }
启动程序,该定时就能够间隔一秒持续执行了。code
使用Spring Schedule就是这么简单,若是有更多其余的需求,配合@Scheduled的其余参数,基本也能够实现。orm
支持传入cron表达式:[秒] [分] [小时] [日] [月] [周] [年],[年]不是必须的域,能够省略[年],则一共6个域。blog
位置 | 说明 | 必填 | 容许填写的值 | 容许的通配符 |
---|---|---|---|---|
1 | 秒 | 是 | 0-59 | - * / |
2 | 分 | 是 | 0-59 | - * / |
3 | 时 | 是 | 0-23 | - * / |
4 | 日 | 是 | 1-31 | - * ? / L W |
5 | 月 | 是 | 1-12 or JAN-DEC | - * / |
6 | 周 | 是 | 1-7 or SUN-SAT | - * ? / L # |
7 | 年 | 否 | 1970-2099 | - * / |
表示时区,接收一个java.util.TimeZone#ID。cron表达式会基于该时区解析。默认是一个空字符串,即取服务器所在地的时区。字符串
上一次执行完毕时间点以后多长时间再执行。it
与fixedDelay相似,传入字符串,也可支持传入${}占位符读取配置文件。table
@Scheduled(fixedDelayString = "${task.two.fixedDelay}") void taskTwo() { System.out.println("如今时间:" + dateFormat.format(new Date())); }
上一次开始执行时间点以后多长时间再执行。
fixedRate与fixedDelay的区别就是:fixedDelay是在上一个任务结束后才开始进行间隔计时,也就是说两次任务之间的时间差等于间隔+任务执行耗时,而fixedRate是在上一个任务一开始就已经开始进行间隔计时了,能够视为固定等于设置的间隔时间。
与fixedRate同样,传入字符串,支持占位符读取配置文件。
第一次任务延迟时间。
同initialDelay,支持占位符读取配置信息。