1 Introduction
spring implements scheduled tasks through annotations, and operates automatically after a fixed time. For example, the mall clears the unreceived orders after a certain time.
2 use
2.1 add annotation @ enableshcheduling
Add a comment @ enableshcheduling on the entry class or Task header to enable support for scheduled tasks
@EnableScheduling public class Application {} //perhaps @EnableScheduling//Start scheduled task public class TimeTask {}
2.2 add annotation @ Component or @ Service
Add @ Component or @ Service on the Task
@Component//Or @ Service @EnableScheduling//Start scheduled task public class TimeTask {}
2.3 add annotation @ Scheduled
Add @ Scheduled on the Scheduled method of the Task class
@Component public class TimeTask { @Scheduled(fixedRateString = "1000", initialDelay = 1000) public void getTokenTask() {} }
3 detailed explanation @ Scheduled
3.1 fixedDelay and fixedDelayString
Re execute after 5s when the last task is completed
@Scheduled(fixedDelay = 5000 ) public void jobFixedDelay(){ System.out.println("Last task completed 5 s Re execute after") }
It has the same meaning as fixed delay, except in the form of string. The only difference is that placeholders are supported.
@Scheduled(fixedDelayString = "5000") public void jobFixedDelayString(){ System.out.println("Last task completed 5 s Re execute after") }
Use of placeholders:
Use of placeholders (configuration in configuration file: time.fixedDelay=5000):
@Scheduled(fixedDelayString = "${time.fixedDelay}") void jobFixedDelayString() { System.out.println("Execute at " + System.currentTimeMillis()); }
3.2 fixedRate and fixedRateString
Re execute after 5s at the beginning of the task
@Scheduled(fixedRate = 5000) public void jobFixedRate(){ System.out.println("Task start 5 s Re execute after") }
fixedRateString has the same meaning as fixedRate, but uses the form of string. The only difference is that placeholders are supported.
Note: in this case, the task will be blocked in case of poor network conditions
Solution: add the annotation @ EnableAsync (on class) and @ Async (on method), and the default number of spring threads is 8
Thread related configuration items under resources:
- spring. task. excution. pool. Core size = 20# thread name prefix
- spring. task. execution. pool. Max size = 1000# maximum number of threads
- spring. task. execution. pool. Keep alive = 3s# idle thread retention time
- spring. task. execution. pool. Queue capacity = 1000 # queue capacity
- spring. task. execution. Thread name prefix = test thread -# thread name prefix
@Component @EnableAsync public class TimeTask { @Async @Scheduled(fixedRateString = "1000", initialDelay = 1000) public void getTokenTask() {} }
3.3 initialDelay and initialDelayString
How long is the first delay before execution
@Scheduled(initialDelay=1000, fixedRate=5000) //It will be executed after the first delay of 1 second, and then it will be executed every 5 seconds according to the rule of fixedRate public void jobInitialDelay(){ System.out.println("First delay 1 s Execute after time") }
3. cron
This parameter accepts a cron expression, which is a string separated by 5 or 6 spaces and separated by 6 or 7 fields. Each field represents a meaning
cron expression syntax
@Scheduled(cron="[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
field | Required | Allowed values | Wildcards allowed |
---|---|---|---|
second | yes | 0-59 | ,-*/ |
branch | yes | 0-59 | ,-*/ |
Time | yes | 0-23 | ,-*/ |
day | yes | 1-31 | ,-*/?LW |
month | yes | 1-12 / JAN-DEC | ,-*/ |
week | yes | 1-7 or SUN-STA | ,-*/?L# |
year | no | 1970-2099 | ,-*/ |
Wildcard:
- *Represents all values. eg: Set * in the second field, which means it will be triggered every second.
- ? 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. eg: you need to trigger an operation on the 10th of each month, but you don't care about the day of the week, so you need to set the field of week position to "?" The specific setting is 0 10 *?
- -Represents an interval. eg: set "10-12" on the hour, which means that it will be triggered at 10, 11 and 12 o'clock.
- , indicating that multiple values are specified, eg: set "MON,WED,FRI" in the week field, indicating that it is triggered on Monday, Wednesday and Friday
5. / used for incremental trigger. eg: set "5 / 15" above the second to trigger every 15 seconds (5,20,35,50) from 5 seconds. Set '1 / 3' in the day field to start on the 1st of each month and trigger every three days. - L means last. eg: in the setting of the day field, 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 profit year [leap]), and in the week field, 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, setting the format of "6L" in the week field means "the last Friday of this month"
- W stands for the nearest working day (Monday to Friday) from the specified date eg: set "15W" on the day field, which 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 (indicating the week of the month), eg: set "6#3" in the week field to indicate 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 month; The setting of week field is case insensitive if English letters are used, that is, mon is the same as mon.
eg:
@Scheduled(cron="*/6 * * * * ?")//Every 6s @Scheduled(cron="0 */1 * * * ?")//Execute every 1min. The first execution is the system time, and the second is 0 @Scheduled(cron="0 1/10 * * * ?")//Execute every 10min and delay for 1 minute. The first execution is that the system time is 0 seconds and the single digit of minute is 1 or 6 @Scheduled(cron="1 1/10 * * * ?")//Execute every 10min and delay for 1 minute. The first execution is that the system time is 1 second and the single digit of minute is 1 or 6 @Scheduled(cron="0 0 6 * * ?")//At 6 o'clock sharp every day @Scheduled(cron="0 0 4 ? * L")//Every Saturday at 4 a.m @Scheduled(cron="0 26,29,33 * * * ?")//Once at 26 points, 29 points and 33 points @Scheduled(cron="0 0 1 1 * ?")//Once at 1 a.m. on the 1st of each month
Note: 0 * / 1 * *? With 0 0 / 1 * *? The effect is the same.
Use placeholders
- Configuration file: time cron= 0 */1 * * * ?
- code
@Scheduled(cron="${time.cron}") public void timeCron() { System.out.println(System.currentTimeMillis()); }