SpringBoot 中定时执行注解(@Scheduled、@EnableScheduling)

点击上方蓝色字体,选择“标星公众号”
java

优质文章,第一时间送达web

  做者 |  野狼谷spring

来源 |  urlify.cn/qqMBnqexpress

76套java从入门到精通实战课程分享服务器

项目开发中常常须要执行一些定时任务,好比须要在天天凌晨时候,分析一次前一天的日志信息。Spring为咱们提供了异步执行任务调度的方式,提供TaskExecutor 、TaskScheduler 接口。微信

SpringBoot中使用两个注解:@EnableScheduling、@Scheduled来简单实现定时任务。

app

@Scheduled参数详解

1. cron

该参数接收一个cron表达式cron表达式是一个字符串,字符串以5或6个空格隔开,分开共6或7个域,每个域表明一个含义。异步

cron表达式语法
[秒] [分] [小时] [日] [月] [周] [年]

注:[年]不是必须的域,能够省略[年],则一共6个域编辑器

序号 说明 必填 容许填写的值 容许的通配符
1 0-59 , - * /
2 0-59 , - * /
3 0-23 , - * /
4 1-31 , - * ? / L W
5 1-12 / JAN-DEC , - * /
6 1-7 or SUN-SAT , - * ? / L #
7 1970-2099 , - * /
通配符说明:
  • * 表示全部值。例如:在分的字段上设置 *,表示每一分钟都会触发。ide

  • ? 表示不指定值。使用的场景为不须要关心当前设置这个字段的值。例如:要在每个月的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相同。

示例

每隔5秒执行一次:*/5 * * * * ?

每隔1分钟执行一次:0 */1 * * * ?

天天23点执行一次:0 0 23 * * ?

天天凌晨1点执行一次:0 0 1 * * ?

每个月1号凌晨1点执行一次:0 0 1 1 * ?

每个月最后一天23点执行一次:0 0 23 L * ?

每周星期天凌晨1点实行一次:0 0 1 ? * L

在26分、29分、33分执行一次:0 26,29,33 * * * ?

天天的0点、13点、18点、21点都执行一次:0 0 0,13,18,21 * * ?

cron表达式使用占位符

另外,cron属性接收的cron表达式支持占位符。eg:

配置文件:

time:
  cron: */5 * * * * *
  interval: 5

每5秒执行一次:

    @Scheduled(cron="${time.cron}")
    void testPlaceholder1() {
        System.out.println("Execute at " + System.currentTimeMillis());
    }

    @Scheduled(cron="*/${time.interval} * * * * *")
    void testPlaceholder2() {
        System.out.println("Execute at " + System.currentTimeMillis());
    }

2. zone

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

3. fixedDelay

上一次执行完毕时间点以后多长时间再执行。如:

@Scheduled(fixedDelay = 5000) //上一次执行完毕时间点以后5秒再执行

4. fixedDelayString

与 3. fixedDelay 意思相同,只是使用字符串的形式。惟一不一样的是支持占位符。如:

@Scheduled(fixedDelayString = "5000") //上一次执行完毕时间点以后5秒再执行

占位符的使用(配置文件中有配置:time.fixedDelay=5000):

    @Scheduled(fixedDelayString = "${time.fixedDelay}")
    void testFixedDelayString() {
        System.out.println("Execute at " + System.currentTimeMillis());
    }

运行结果:

占位符的使用

5. fixedRate

上一次开始执行时间点以后多长时间再执行。如:

@Scheduled(fixedRate = 5000) //上一次开始执行时间点以后5秒再执行

6. fixedRateString

与 5. fixedRate 意思相同,只是使用字符串的形式。惟一不一样的是支持占位符。

7. initialDelay

第一次延迟多长时间后再执行。如:

@Scheduled(initialDelay=1000, fixedRate=5000) //第一次延迟1秒后执行,以后按fixedRate的规则每5秒执行一次

8. initialDelayString

与 7. initialDelay 意思相同,只是使用字符串的形式。惟一不一样的是支持占位符。

That's all ! Thanks for reading.

附:

截至spring-context-4.3.14.RELEASE的源码

/**
 * An annotation that marks a method to be scheduled. Exactly one of
 * the {@link #cron()}, {@link #fixedDelay()}, or {@link #fixedRate()}
 * attributes must be specified.
 *
 * <p>The annotated method must expect no arguments. It will typically have
 * a {@code void} return typeif not, the returned value will be ignored
 * when called through the scheduler.
 *
 * <p>Processing of {@code @Scheduled} annotations is performed by
 * registering a {@link ScheduledAnnotationBeanPostProcessor}. This can be
 * done manually or, more conveniently, through the {@code <task:annotation-driven/>}
 * element or @{@link EnableScheduling} annotation.
 *
 * <p>This annotation may be used as a <em>meta-annotation</em> to create custom
 * <em>composed annotations</em> with attribute overrides.
 *
 * @author Mark Fisher
 * @author Dave Syer
 * @author Chris Beams
 * @since 3.0
 * @see EnableScheduling
 * @see ScheduledAnnotationBeanPostProcessor
 * @see Schedules
 */
@Target({ElementType.METHOD, ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Repeatable(Schedules.class)
public @interface Scheduled {

    /**
     * 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).
     * @return an expression that can be parsed to a cron schedule
     * @see org.springframework.scheduling.support.CronSequenceGenerator
     */
    String cron() 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).
     * @return a zone id accepted by {@link java.util.TimeZone#getTimeZone(String)},
     * or an empty String to indicate the server'
s default time zone
     * @since 4.0
     * @see org.springframework.scheduling.support.CronTrigger#CronTrigger(String, java.util.TimeZone)
     * @see java.util.TimeZone
     */
    String zone() default "";

    /**
     * Execute the annotated method with a fixed period in milliseconds between the
     * end of the last invocation and the start of the next.
     * @return the delay in milliseconds
     */
    long fixedDelay() 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.
     * @return the delay in milliseconds as a String value, e.g. a placeholder
     * @since 3.2.2
     */
    String fixedDelayString() default "";

    /**
     * Execute the annotated method with a fixed period in milliseconds between
     * invocations.
     * @return the period in milliseconds
     */
    long fixedRate() default -1;

    /**
     * Execute the annotated method with a fixed period in milliseconds between
     * invocations.
     * @return the period in milliseconds as a String value, e.g. a placeholder
     * @since 3.2.2
     */
    String fixedRateString() default "";

    /**
     * Number of milliseconds to delay before the first execution of a
     * {@link #fixedRate()} or {@link #fixedDelay()} task.
     * @return the initial delay in milliseconds
     * @since 3.2
     */
    long initialDelay() default -1;
    String initialDelayString() default "";

}





粉丝福利:Java从入门到入土学习路线图

👇👇👇

   
👆长按上方微信二维码 2 秒


感谢点赞支持下哈 

本文分享自微信公众号 - java1234(gh_27ed55ecb177)。
若有侵权,请联系 support@oschina.cn 删除。
本文参与“OSC源创计划”,欢迎正在阅读的你也加入,一块儿分享。

相关文章
相关标签/搜索