Spring scheduled task - @ Schedule annotation details

1, @ Schedule annotation list

@The Scheduled annotation has 8 attributes (3 of which are the same configurations of different types) and a constant CRON_DISABLED. The source code is as follows:

/**
 * Marks the comment for the method to schedule. One of the cron, fixedDelay, or fixedRate properties must be specified exactly. Annotated methods must have no parameters.    
 * It usually has a void return type; If not, the return value is ignored when called through the scheduler@ The Scheduled annotation is processed through registration
 * A ScheduledAnnotationBeanPostProcessor to execute. This can be done manually, or more conveniently, by 
 * <task:annotation-driven/> Element or @ enablesscheduling comment.
 * This annotation can be used as a meta annotation to create a custom composite annotation with attribute overrides.
 * @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 {

	/**
	 * Special cron expression value indicating disable trigger: '-'.
	 * This is mainly used for ${...} Placeholder that allows external to disable the corresponding scheduling method.
	 * 
	 * @since 5.1
	 * @see ScheduledTaskRegistrar#CRON_DISABLED
	 */
	String CRON_DISABLED = ScheduledTaskRegistrar.CRON_DISABLED;

	/**
	 * A cron like expression that extends the usual UN*X definition to include triggers for seconds, minutes, hours, a day of the month, month and day of the week.
	 * For example, "0 * * * * MON-FRI" means once every minute of the working day (at the top of the minute - the 0th second).
	 * 
	 * The fields read from left to right are interpreted as follows:
	 * <ul>
	 * <li>second</li>
	 * <li>minute</li>
	 * <li>hour</li>
	 * <li>day of month</li>
	 * <li>month</li>
	 * <li>day of week</li>
	 * </ul>
	 * The special value "-" indicates a disabled cron trigger, which is mainly used by ${...} The external specified value of the placeholder resolution.
	 * @return Returns an expression that can be parsed into a cron plan
	 * @see org.springframework.scheduling.support.CronSequenceGenerator
	 */
	String cron() default "";

	/**
	 * The time zone where the cron expression will be resolved. Default: '' (that is, use the local time zone of the server).
	 * 
	 * @return java.util.TimeZone.getTimeZone(String) Accepted zone ID, or an empty string indicating the default time zone of the server
	 * @since 4.0
	 * @see org.springframework.scheduling.support.CronTrigger#CronTrigger(String, java.util.TimeZone)
	 * @see java.util.TimeZone
	 */
	String zone() default "";

	/**
	 * Fixed time period between the end of the last call and the beginning of the next call, unit: ms, default: - 1 (no delay)
	 * 
	 * @return Delay duration in milliseconds
	 */
	long fixedDelay() default -1;

	/**
	 * Fixed time interval string between the end of the last call and the beginning of the next call, in milliseconds. 
	 * 
	 * @return Delay value string in milliseconds, such as placeholder or
	 *         {@link java.time.Duration#parse java.time.Duration} Compatibility value
	 * @since 3.2.2
	 */
	String fixedDelayString() default "";

	/**
	 * Fixed time period between calls, in milliseconds.
	 * 
	 * @return Period in milliseconds
	 */
	long fixedRate() default -1;

	/**
	 * Fixed time period string between calls in milliseconds.
	 * 
	 * @return Delay value string in milliseconds, such as placeholder or 
	 *         {@link java.time.Duration#parse java.time.Duration} Compatibility value
	 * @since 3.2.2
	 */
	String fixedRateString() default "";

	/**
	 * The number of milliseconds to delay before the first fixedRate or fixedDelay task is executed.
	 * 
	 * @return Initial delay value in milliseconds
	 * @since 3.2
	 */
	long initialDelay() default -1;

	/**
	 * The millisecond numeric string that is delayed before the first execution of the fixedRate or fixedDelay task.
	 * @return Initial delay value string in milliseconds, such as placeholder or Java time. Value of duration
	 * @since 3.2.2
	 */
	String initialDelayString() default "";

}

2, Detailed explanation of parameters

1. cron

This parameter receives a cron expression string. The string is separated by 5 or 6 spaces, with a total of 6 or 7 fields. Each field represents a meaning. See the corresponding notes for its order and meaning, as follows:

  [second] [branch] [hour] [day] [month] [week] [year]

Among them, [year] is not a required field, and [year] can be omitted. If [year] is omitted, there are 6 fields in total.

fieldRequiredRange of valuesWildcards allowed
secondyes0-59, - * /
branchyes0-59, - * /
Timeyes0-23, - * /
dayyes1-31, - * ? / L W
monthyes1-12 / JAN-DEC, - * /
weekyes1-7 or SUN-SAT, - * ? / L #
yearno1970-2099, - * /

Wildcard Description:
*: all values. For example, if * is set on [min], execution will be triggered every minute.
?: No value specified. The scenario used is that you don't need to care about the value of this field currently set. For example, to trigger execution on the 1st of each month, regardless of the day of the week, you need to set the [week] to?, The specific setting is: "0 1 *?".
-: interval. For example, if "1-3" is set on [time], the execution will be triggered at points 1, 2 and 3.
,: specify multiple values. For example, setting "MON,WED,FRI" on [week] indicates that Monday, Wednesday and Friday are triggered.
/: used for incremental triggering. If "5 / 15" is set on [Second], it means that it will be triggered every 15 seconds from 5 seconds (5,20,35,50). Set '1 / 3' on [day], starting from the 1st of each month, and trigger every three days.
50: Last. In the [day] field setting, it represents the last day of the current month (according to the current month, if it is February, it will also depend on whether it is a Runnian [leap]), and in [week], it represents Saturday, which is equivalent to "7" or "SAT". If a number is added before "L", it indicates the last of the data. For example, if the format "6L" is set on [week], it means "the last Friday of this month"
W: The nearest working day (Monday to Friday) from the specified date. For example, setting "15W" on [day] indicates that it is triggered on the working day closest to the 15th of each month. If the 15th happens to be Saturday, it will be triggered by the latest Friday (14th). If the 15th is weekend, it will be triggered by the latest next Monday (16th) If the 15th happens to be a working day (Monday to Friday), it will be triggered on that day. If the specified format is "1W", it indicates that it is triggered on the latest working day after the 1st of each month. If the 1st is Saturday, it will be triggered on the 3rd next Monday. (Note: only specific numbers can be set before "W", and interval "-" is not allowed).
#: serial number (indicates the week of the month). For example, setting "6#3" on [week] indicates the third Saturday of the month. Note that if "#5" is specified, there is no Saturday in the fifth week, this configuration will not be triggered (applicable to holidays without fixed dates: such as mother's day and father's day).

TIPS:
1) 'L' and 'W' can be used in combination. If "LW" is set on [day], it means it will be triggered on the last working day of the month
2) The setting of the week field is case insensitive if English letters are used, that is, mon is the same as mon.
3) Cron attribute, as stated in the comment, supports ${} expression. You can dynamically obtain the configured cron expression from the spring configuration file:

task:
    # Perform tasks at 2 a.m. every day
    cron: 0 0 2 * * ?
    # Minutes between tasks
    interval: 15
    # 
    fixed-delay: 5000

Task code method:

 /**
  * cron expression for test configuration
  */
 @Scheduled(cron = "${task.cron}")
 public void test_1() {
     System.out.println("Task running: " + System.currentTimeMillis());
 }
 /**
  * Test minute configuration expression
  */
 @Scheduled(cron = "* 0/${task.interval} * * * *")
 void test_2() {
    System.out.println("Task running: " + System.currentTimeMillis());
 }

2. zone

Time zone, receive a Java util. TimeZone#ID. The cron expression resolves based on the time zone. The default is an empty string, that is, the time zone where the server is located. For example, we generally use the time zone Asia/Shanghai. This field is generally left blank.

3. fixedDelay / fixedDelayString

How long will it be executed after the last execution time? Long type. For example:

 // Execute the next task 15 seconds after the last task
 @Scheduled(fixedDelay = 15000) 

fixedDelayString has the same meaning as fixedDelay. It is a String type. The only difference is that placeholders are supported. For example:

 // Execute the next task 15 seconds after the last task
 @Scheduled(fixedDelayString = "15000") 

Use of placeholders (configuration above: task. Fixed delay = 15000):

 @Scheduled(fixedDelayString = "${task.fixed-delay}")
 void testFixedDelayString() {
    System.out.println("Task running: " + System.currentTimeMillis());
 }

4. fixedRate / fixedRateString

How long will it be executed after the last execution time point? Long type. For example:

 // Execute the next task 15 seconds after the last task
 @Scheduled(fixedRate = 15000)

fixedRateString has the same meaning as fixedRate. String type. The only difference is that placeholders are supported.

5. initialDelay / initialDelayString

How long is the first delay before execution? Long type. For example:

 //  Execute after 5 seconds delay for the first time, and then execute every 10 seconds according to the rule of fixedRate
 @Scheduled(initialDelay = 5000, fixedRate = 10000)

initialDelayString has the same meaning as initialDelay. String type. The only difference is that placeholders are supported.

Keywords: Java Spring Back-end

Added by Daniel Exe on Thu, 23 Dec 2021 20:25:45 +0200