spring中定时器@Scheduled注解各参数详解

@Scheduled注解的使用这里不详细说明,直接对8个参数进行讲解。

参数详解

1. cron

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

cron表达式语法

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

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

序号说明必填允许填写的值允许的通配符
10-59, - * /
20-59, - * /
30-23, - * /
41-31, - * ? / L W
51-12 / JAN-DEC, - * /
61-7 or SUN-SAT, - * ? / L #
71970-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相同。

示例

每隔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 type; if 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 "";

}

 

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: spring定时器@scheduled是一种基于注解的定时任务调度方式,可以在指定的时间间隔或固定时间点执行任务。通过在方法上添加注解@scheduled,可以指定任务的执行时间、执行频率、执行条件等。这种方式简单易用,适用于各种场景下的定时任务调度。 ### 回答2: Spring定时器@scheduled是一种非常常用和方便的定时任务调度方式,它是Spring框架的一部分。使用@scheduled注解可以让方法按照一定的时间间隔或者某个特定时间点去执行,可以说是非常方便实用了。 @scheduled注解必须放在方法上,可以设置多个属性来指定任务的执行时间和间隔。其,cron属性是一个非常重要的属性,它使用了系统的cron表达式来指定任务的执行时间,这样我们可以实现非常精细的任务调度,实现复杂的任务流程。 除了cron之外,还有fixedDelay和fixedRate属性,分别表示延迟多少毫秒后再次执行和间隔多少毫秒再次执行,这两个属性适用于固定间隔执行的任务。 @scheduled注解还支持设置initialDelay属性,表示任务延迟多少秒后开始执行。这在某些情况下非常有用,如需要在系统启动后延迟一定时间再执行的任务。 除了定时任务之外,@scheduled还支持retry注解,可以在任务执行失败时自动重新执行几次,这对于保证任务的可靠性非常重要。 需要注意的是,@scheduled注解只能用于Spring Bean的方法,也就是说,这样的方法必须是由Spring容器来管理的,只有被纳入了Spring容器的Bean才能被@scheduled注解所标注。 总之,Spring定时器@scheduled的使用非常广泛,实用性非常高。需要我们根据业务需求来灵活运用,并注意任务的可靠性和性能问题。 ### 回答3: Spring框架提供了一个方便的定时任务处理的功能模块:@Scheduled。这个注解就是用来创建一个定时任务方法的。 基本使用方式 在一个方法上添加 @Scheduled 注解, 并设置触发执行时间。例如,下面代码是定义了一个每5秒执行一次的定时任务: @Scheduled(fixedRate = 5000) public void doSomething() { //TODO: 实现定时任务所需的业务逻辑... } 同时要注意,要开启对 @Scheduled 的支持,需要在 Spring 配置文件添加以下配置: <task:annotation-driven/> 其他属性 除了 fixedRate 属性,还有另外两个常用属性: - fixedDelay:在两次执行之间存在延迟(即两次执行之间需要等等),单位是毫秒; - cron:使用 Cron 表达式支持,更加灵活,更精准地设置执行的时间,类似于Linux的Crontab。比如: - @Scheduled(cron="0 15 10 ? * *") // 每天10点15分执行 - @Scheduled(cron="0 0/5 14,18 * * ?") // 每天下午2点到3点,每个五分钟执行一次 总结 @Scheduled 可以让程序员非常方便地实现定时任务的功能,使用起来也很容易理解。 同时因为 Spring 框架支持的任务类型非常丰富,包括定时任务、异步执行、并发运行、任务队列等等,可谓是应对各种需求场景的优秀工具。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值