In the actual project development work, we often encounter the need to do some scheduled tasks. Then, how is it implemented in Spring Boot?
- Add dependency
In POM You only need to introduce the dependency of spring boot starter in the XML file:
Code listing: spring boot scheduler / POM xml
Understand the source code + VX: 445909108
Java code
<dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies>
- Configuration file (understand the source code + request: 1791743380)
The configuration file does not require too many configurations:
Code listing: spring boot scheduler / SRC / main / resources / application yml
Java code
server: port: 8080 spring: application: name: spring-boot-scheduler
- Start main class
The annotation @ enableshcheduling needs to be added to start the main class, indicating that we want to start the scheduled task service.
Code listing: spring boot scheduler / SRC / main / Java / COM / springboot / springbootscheduler / springbootschedulerapplication java
Java code
@SpringBootApplication @EnableScheduling public class SpringBootSchedulerApplication { public static void main(String[] args) { SpringApplication.run(SpringBootSchedulerApplication.class, args); } }
- Scheduled task implementation class
Code listing: spring boot scheduler / SRC / main / Java / COM / springboot / springbootscheduler / task / task java
Java code
@Component public class Task { private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss"); private final Logger logger = LoggerFactory.getLogger(Task.class); /** * cron expression */ @Scheduled(cron = "*/5 * * * * ?") private void task1() { logger.info("task1 Executing, now time:{}", dateFormat.format(new Date())); } /** * Execute again 5 seconds after the last execution time point */ @Scheduled(fixedRate = 5000) public void task2() { logger.info("task2 Executing, now time:{}", dateFormat.format(new Date())); } /** * Execute 5 seconds after the last execution time point */ @Scheduled(fixedDelay = 5000) public void task3() { logger.info("task3 Executing, now time:{}", dateFormat.format(new Date())); } /** * It is executed after the first delay of 1 second, and then it is executed every 5 seconds according to the rule of fixedRate */ @Scheduled(initialDelay = 1000, fixedRate = 5000) public void task4() { logger.info("task4 Executing, now time:{}", dateFormat.format(new Date())); } }
4.1 parameter cron
cron expression syntax:
Java code
[second] [branch] [hour] [day] [month] [week] [year]
Note: [year] is not a required field. If [year] can be omitted, there are 6 fields in total
Java code collection code
Description is required. Values that can be filled in are allowed. Wildcards are allowed
Seconds are 0-59, – */
Points are 0-59, – */
0-23 at – */
Day is 1-31, – */ L W
Month is 1-12 / JAN-DEC, – */
Week is 1-7 or SUN-SAT, – */ L #
1970-2099, – */
Wildcard Description:
- Represents all values. For example, setting * in the field of minute indicates that it will be triggered every minute.
? Indicates that no value is specified. The scenario used is that you don't need to care about the value of this field currently set. For example, if you want to trigger an operation on the 10th of each month, but you don't care about the day of the week, you need to set the field of the week position to " The specific setting is 0 10 *?
- Represents an interval. For example, "10-12" is set on the hour, which means that it will be triggered at 10, 11 and 12 o'clock.
, indicating that multiple values are specified. For example, setting "MON,WED,FRI" in the week field indicates that Monday, Wednesday and Friday are triggered
/Used for incremental triggering. If "5 / 15" is set above the second, it means that starting from 5 seconds, it will be triggered every 15 seconds (5,20,35,50). Set '1 / 3' in the month field to start on the 1st of each month and trigger it every three days.
L means last. In the day field setting, it indicates the last day of the current month (according to the current month, if it is February, it also depends on whether it is a profit year [leap]). In the week field, it indicates 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 in the week field, it means "the last Friday of this month"
W is the nearest working day (Monday to Friday) from the specified date For example, setting "15W" on the day field 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 the interval "-" is not allowed). # serial number (indicates the week of the month). For example, setting "6#3" in the week field indicates the third Saturday of the month Note that if "#5" is specified and there is no Saturday in the fifth week, this configuration will not be triggered (it is most suitable for mother's day and father's day); Tip: 'L' and 'W' can be used together. If "LW" is set in the day field, it means it will be triggered on the last working day of the current month; The setting of the week field is case insensitive if English letters are used, that is, mon is the same as mon.
4.2 parameter 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.
4.3 parameters fixedDelay and fixedDelayString
The two parameters actually have the same meaning, except that one uses the Long type and the other uses the String type.
The meaning is how long after the last execution time point, and the specific use examples have been given in the above code.
4.4 parameters fixedRate and fixedRateString
This group of parameters is the same as the above group of parameters. The same type is different. It means how long it will be executed after the last execution time point.
4.5 parameters initialDelay and initialDelayString
The meaning of this set of parameters is how long to delay the execution for the first time.
4.6 attach org springframework. scheduling. annotation. Scheduled
@The usage of the Scheduled annotation has been clearly described in the source code. Here is attached for your reference:
Java code
@Target({ElementType.METHOD, ElementType.ANNOTATION_TYPE}) @Retention(RetentionPolicy.RUNTIME) @Documented @Repeatable(Schedules.class) public @interface Scheduled { /** * A special cron expression value that indicates a disabled trigger: {@value}. * <p>This is primarily meant for use with ${...} placeholders, allowing for * external disabling of corresponding scheduled methods. * @since 5.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. * <p>E.g. {@code "0 * * * * MON-FRI"} means once per minute on weekdays * (at the top of the minute - the 0th second). * <p>The special value {@link #CRON_DISABLED "-"} indicates a disabled cron trigger, * primarily meant for externally specified values resolved by a ${...} placeholder. * @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 * or a {@link java.time.Duration#parse java.time.Duration} compliant value * @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 * or a {@link java.time.Duration#parse java.time.Duration} compliant value * @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; /** * Number of milliseconds to delay before the first execution of a * {@link #fixedRate()} or {@link #fixedDelay()} task. * @return the initial delay in milliseconds as a String value, e.g. a placeholder * or a {@link java.time.Duration#parse java.time.Duration} compliant value * @since 3.2.2 */ String initialDelayString() default ""; }