In the actual project development work, we often encounter the work that needs to do some timing tasks, so how to achieve in Spring Book?
1. Adding dependencies
In the pom.xml file, only spring-boot-starter dependencies need to be introduced:
List of code: spring-boot-scheduler/pom.xml
<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>
2. Configuration files
Configuration files need not be configured too much:
List of code: spring-boot-scheduler/src/main/resources/application.yml
server: port: 8080 spring: application: name: spring-boot-scheduler
3. Start the main class
Starting the main class requires adding the annotation @EnableScheduling to indicate that we want to start the service of timed tasks.
List of code: spring-boot-scheduler/src/main/java/com/spring boot/spring bootscheduler/Spring Boot Scheduler Application.java
@SpringBootApplication @EnableScheduling public class SpringBootSchedulerApplication { public static void main(String[] args) { SpringApplication.run(SpringBootSchedulerApplication.class, args); } }
4. Timing Task Implementation Class
List of code: spring-boot-scheduler/src/main/java/com/spring boot/spring bootscheduler/task/Task.java
@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())); } /** * Five seconds after the last execution point */ @Scheduled(fixedRate = 5000) public void task2() { logger.info("task2 Executing, now time:{}", dateFormat.format(new Date())); } /** * Five seconds after the last execution point */ @Scheduled(fixedDelay = 5000) public void task3() { logger.info("task3 Executing, now time:{}", dateFormat.format(new Date())); } /** * Execution is delayed by one second for the first time, and then every five seconds according to the fixed Rate rule */ @Scheduled(initialDelay = 1000, fixedRate = 5000) public void task4() { logger.info("task4 Executing, now time:{}", dateFormat.format(new Date())); } }
4.1 parameter cron
cron expression grammar:
[seconds] [minutes] [hours] [days] [months] [weeks] [years]
Note: [Year] is not a necessary domain. If [Year] can be omitted, there are six domains in total.
Explain | Must fill | Values allowed to be filled in | Allowed wildcards |
---|---|---|---|
second | yes | 0-59 | , - * / |
branch | yes | 0-59 | , - * / |
Time | yes | 0-23 | , - * / |
day | yes | 1-31 | , - * ? / L W |
month | yes | 1-12 / JAN-DEC | , - * / |
week | yes | 1-7 or SUN-SAT | , - * ? / L # |
year | no | 1970-2099 | , - * / |
Wildcard Description:
- * Represents all values. For example, setting * on a sub-field means that it triggers every minute.
- Does not specify a value? The scenario used is to set the value of this field without concern. For example: to trigger an operation on the 10th day of each month, but do not care about the day of the week, so you need to set the field of the week position to "?" specifically set to 0 0 0 10 *?
- - Represents intervals. For example, setting "10-12" on an hour means that 10, 11, 12 will trigger.
- That means specifying multiple values, such as setting "MON,WED,FRI" on the week field to trigger on Monday, Wednesday and Friday
- / Used for incremental triggering. If "5/15" is set on the second, it means triggering every 15 seconds (5, 20, 35, 50) starting from 5 seconds. Set'1/3'on the monthly field to start on the 1st of each month and trigger it every three days.
- L means the last word. In the day field setting, it means the last day of the month (according to the current month, if February is also based on whether it is a leap), and in the week field it means Saturday, which is equivalent to "7" or "SAT". If a number is added before "L", it represents the last of the data. For example, setting a format like "6L" on the week field means "the last Friday of the month".
- W stands for the nearest working day (Monday to Friday) from the specified date. For example, "15W" is placed on the day field, indicating that the nearest working day to the 15th of each month is triggered. If the 15th happens to be a Saturday, then look for the nearest Friday (14) to trigger, if the 15th is a weekend, then look for the nearest Monday (16) to trigger. If the 15th happens to be on the working day (Monday to Friday), it will trigger on that day. If the specified format is "1W", it indicates that the latest working day will be triggered from the 1st of each month. If No. 1 is Saturday, it will be triggered next Monday, No. 3. (Note, "W" can only be set before the specific number, do not allow intervals "-").
- # Number (for the first few weeks of each month), such as setting "6 # 3" on the week field to indicate the third Saturday of each month. Note that if you specify "# 5", which happens to be the fifth week without a Saturday, this configuration will not be triggered (which is suitable for Mother's Day and Father's Day); Tip:'L'and'W' can be used together. If "LW" is set on the day field, it means triggering on the last working day of this month; if the setting of the week field is case-insensitive, that is, MON is the same as mon.
4.2 parameter zone
Time zone, receives a java.util.TimeZone#ID. The cron expression is resolved based on that time zone. The default is an empty string, which takes the time zone where the server is located. For example, we usually use the time zone Asia/Shanghai. We usually leave this field blank.
4.3 Parameters fixedDelay and fixedDelayString
The two parameters actually mean the same thing, except that one uses the Long type and the other uses the String type.
The implication is how long it will take to execute after the last execution point. The specific use examples are given in the code above.
4.4 parameters fixedRate and fixedRateString
This set of parameters and the above set of parameters are the same, the same is different types, meaning how long to execute after the last execution time point.
4.5 Parameters initialDelay and initialDelayString
The meaning of this set of parameters is how long is the first delay before execution.
4.6 Attached is org. spring framework. scheduling. annotation. Scheduled
@The usage of the Scheduled annotation is actually very clear in the source code. Here is a reference:
@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 ""; }
5. Sample code
6. reference
https://www.jianshu.com/p/1de...
If my article is helpful to you, please pay close attention to the author's public number: Get the latest dry goods push:)