Spring Boot 定时任务

1. 添加依赖

在 pom.xml 文件中只需引入 spring-boot-starter 的依赖即可:

代码清单:spring-boot-scheduler/pom.xml

org.springframework.bootspring-boot-starterorg.springframework.bootspring-boot-starter-testtest

2. 配置文件

配置文件无需过多的配置:

代码清单:spring-boot-scheduler/src/main/resources/application.yml

server:  port:8080spring:  application:    name:spring-boot-scheduler

3. 启动主类

启动主类需增加注解 @EnableScheduling 表示我们要开启定时任务这个服务。

代码清单:spring-boot-scheduler/src/main/java/com/springboot/springbootscheduler/SpringBootSchedulerApplication.java

@SpringBootApplication@EnableSchedulingpublicclassSpringBootSchedulerApplication{publicstaticvoidmain(String[] args){        SpringApplication.run(SpringBootSchedulerApplication.class, args);    }}

4. 定时任务实现类

代码清单:spring-boot-scheduler/src/main/java/com/springboot/springbootscheduler/task/Task.java

@ComponentpublicclassTask{privatestaticfinalSimpleDateFormat dateFormat =newSimpleDateFormat("HH:mm:ss");privatefinalLogger logger = LoggerFactory.getLogger(Task.class);/**

    * cron表达式

    */@Scheduled(cron ="*/5 * * * * ?")privatevoidtask1(){        logger.info("task1 正在执行,现在时间:{}", dateFormat.format(newDate()));    }/**

    * 上一次开始执行时间点之后5秒再执行

    */@Scheduled(fixedRate =5000)publicvoidtask2(){        logger.info("task2 正在执行,现在时间:{}", dateFormat.format(newDate()));    }/**

    * 上一次执行完毕时间点之后5秒再执行

    */@Scheduled(fixedDelay =5000)publicvoidtask3(){        logger.info("task3 正在执行,现在时间:{}", dateFormat.format(newDate()));    }/**

    * 第一次延迟1秒后执行,之后按fixedRate的规则每5秒执行一次

    */@Scheduled(initialDelay =1000, fixedRate =5000)publicvoidtask4(){        logger.info("task4 正在执行,现在时间:{}", dateFormat.format(newDate()));    }}

4.1 参数 cron

cron表达式语法:

[秒] [分] [小时] [日] [月] [周] [年]COPY

注:[年]不是必须的域,可以省略[年],则一共6个域

说明必填允许填写的值允许的通配符

秒是0-59, – * /

分是0-59, – * /

时是0-23, – * /

日是1-31, – * ? / L W

月是1-12 / JAN-DEC, – * /

周是1-7 or SUN-SAT, – * ? / L #

年否1970-2099, – * /

通配符说明:

* 表示所有值。 例如:在分的字段上设置 *,表示每一分钟都会触发。

? 表示不指定值。使用的场景为不需要关心当前设置这个字段的值。例如:要在每月的10号触发一个操作,但不关心是周几,所以需要周位置的那个字段设置为”?” 具体设置为 0 0 0 10 * ?

- 表示区间。例如 在小时上设置 “10-12”,表示 10,11,12点都会触发。

, 表示指定多个值,例如在周字段上设置 “MON,WED,FRI” 表示周一,周三和周五触发

/ 用于递增触发。如在秒上面设置”5/15” 表示从5秒开始,每增15秒触发(5,20,35,50)。 在月字段上设置’1/3’所示每月1号开始,每隔三天触发一次。

L 表示最后的意思。在日字段设置上,表示当月的最后一天(依据当前月份,如果是二月还会依据是否是润年[leap]), 在周字段上表示星期六,相当于”7”或”SAT”。如果在”L”前加上数字,则表示该数据的最后一个。例如在周字段上设置”6L”这样的格式,则表示“本月最后一个星期五”

W 表示离指定日期的最近那个工作日(周一至周五). 例如在日字段上置”15W”,表示离每月15号最近的那个工作日触发。如果15号正好是周六,则找最近的周五(14号)触发, 如果15号是周未,则找最近的下周一(16号)触发.如果15号正好在工作日(周一至周五),则就在该天触发。如果指定格式为 “1W”,它则表示每月1号往后最近的工作日触发。如果1号正是周六,则将在3号下周一触发。(注,”W”前只能设置具体的数字,不允许区间”-“)。

# 序号(表示每月的第几个周几),例如在周字段上设置”6#3”表示在每月的第三个周六.注意如果指定”#5”,正好第五周没有周六,则不会触发该配置(用在母亲节和父亲节再合适不过了) ;小提示:’L’和 ‘W’可以一组合使用。如果在日字段上设置”LW”,则表示在本月的最后一个工作日触发;周字段的设置,若使用英文字母是不区分大小写的,即MON与mon相同。

4.2 参数 zone

时区,接收一个java.util.TimeZone#ID。cron表达式会基于该时区解析。默认是一个空字符串,即取服务器所在地的时区。比如我们一般使用的时区Asia/Shanghai。该字段我们一般留空。

4.3 参数 fixedDelay 和 fixedDelayString

这两个参数其实含义是一样的,只是一个使用的是 Long 类型,一个使用的是 String 类型。

含义都是上一次执行完毕时间点之后多长时间再执行,具体使用示例在上面的代码中已经给出。

4.4 参数 fixedRate 和 fixedRateString

这一组参数和上面的那组参数也是一样的,同样的是类型不同,含义是上一次开始执行时间点之后多长时间再执行。

4.5 参数 initialDelay 和 initialDelayString

这组参数的含义是第一次延迟多长时间后再执行。

4.6 附上 org.springframework.scheduling.annotation.Scheduled

@Scheduled 注解的使用方式其实在源码里已经讲的很清楚了,这里附上供大家参考:

@Target({ElementType.METHOD, ElementType.ANNOTATION_TYPE})@Retention(RetentionPolicy.RUNTIME)@Documented@Repeatable(Schedules.class)public@interfaceScheduled {/**    * A special cron expression value that indicates a disabled trigger: {@value}.    *

This is primarily meant for use with ${...} placeholders, allowing for    * external disabling of corresponding scheduled methods.    *@since5.1    */String CRON_DISABLED ="-";/**    * A cron-like expression, extending the usual UN*X definition to include triggers    * on the second as well as minute, hour, day of month, month and day of week.    *

E.g. {@code"0 * * * * MON-FRI"} means once per minute on weekdays    * (at the top of the minute - the 0th second).    *

The special value {@link#CRON_DISABLED "-"} indicates a disabled cron trigger,    * primarily meant for externally specified values resolved by a ${...} placeholder.    *@returnan expression that can be parsed to a cron schedule    *@seeorg.springframework.scheduling.support.CronSequenceGenerator    */Stringcron()default"";/**    * A time zone for which the cron expression will be resolved. By default, this    * attribute is the empty String (i.e. the server's local time zone will be used).    *@returna zone id accepted by {@linkjava.util.TimeZone#getTimeZone(String)},    * or an empty String to indicate the server's default time zone    *@since4.0    *@seeorg.springframework.scheduling.support.CronTrigger#CronTrigger(String, java.util.TimeZone)    *@seejava.util.TimeZone    */Stringzone()default"";/**    * Execute the annotated method with a fixed period in milliseconds between the    * end of the last invocation and the start of the next.    *@returnthe delay in milliseconds    */longfixedDelay()default-1;/**    * Execute the annotated method with a fixed period in milliseconds between the    * end of the last invocation and the start of the next.    *@returnthe delay in milliseconds as a String value, e.g. a placeholder    * or a {@linkjava.time.Duration#parse java.time.Duration} compliant value    *@since3.2.2    */StringfixedDelayString()default"";/**    * Execute the annotated method with a fixed period in milliseconds between    * invocations.    *@returnthe period in milliseconds    */longfixedRate()default-1;/**    * Execute the annotated method with a fixed period in milliseconds between    * invocations.    *@returnthe period in milliseconds as a String value, e.g. a placeholder    * or a {@linkjava.time.Duration#parse java.time.Duration} compliant value    *@since3.2.2    */StringfixedRateString()default"";/**    * Number of milliseconds to delay before the first execution of a    * {@link#fixedRate()} or {@link#fixedDelay()} task.    *@returnthe initial delay in milliseconds    *@since3.2    */longinitialDelay()default-1;/**    * Number of milliseconds to delay before the first execution of a    * {@link#fixedRate()} or {@link#fixedDelay()} task.    *@returnthe initial delay in milliseconds as a String value, e.g. a placeholder    * or a {@linkjava.time.Duration#parse java.time.Duration} compliant value    *@since3.2.2    */StringinitialDelayString()default"";}

(企业架构源码可以加求球:三五三六二四七二五九)

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 158,560评论 4 361
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,104评论 1 291
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,297评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,869评论 0 204
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,275评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,563评论 1 216
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,833评论 2 312
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,543评论 0 197
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,245评论 1 241
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,512评论 2 244
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,011评论 1 258
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,359评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,006评论 3 235
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,062评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,825评论 0 194
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,590评论 2 273
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,501评论 2 268

推荐阅读更多精彩内容