In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-04-10 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
In this issue, the editor will bring you about SpringBoot timing tasks and Cron expressions. The article is rich in content and analyzed and described from a professional point of view. I hope you can get something after reading this article.
How to use SpringBoot to schedule tasks, and through the source code to explain how to use multi-threading to handle each scheduled task. Details the usage of cron expressions.
I. Overview of scheduled tasks
Timed tasks are often used in background project development, and now timed tasks are realized in a variety of ways. Here are several common ways to implement scheduled tasks:
1. Quartz:Quartz is widely used, it is a powerful scheduler, of course, it is relatively troublesome to use.
2. Timer in the java.util package, it can also achieve scheduled tasks, but the function is too single, so it is rarely used.
3. That is, we are going to introduce Spring's own scheduled task Schedule, in fact, it can be regarded as a simplified, lightweight version of Quartz, and it is relatively easy to use.
Second, the realization of scheduled tasks
1. Create a scheduled task
Import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; / * Description: build execution scheduled task * Designer: jack * Date: 2017-8-10 * Version: 1.0.0 * / @ Component public class ScheduledTasks {private Logger logger = LoggerFactory.getLogger (ScheduledTasks.class); private int fixedDelayCount = 1; private int fixedRateCount = 1; private int initialDelayCount = 1 Private int cronCount = 1; @ Scheduled (fixedDelay = 5000) / / fixedDelay = 5000 means that after the current method has finished executing 5000ms, Spring scheduling will call the method public void testFixDelay () {logger.info ("= = fixedDelay: the {} execution method", fixedDelayCount++). } @ Scheduled (fixedRate = 5000) / / fixedRate = 5000 means that after the current method starts executing 5000ms, Spring scheduling will call the method public void testFixedRate () {logger.info ("= fixedRate: the {} execution method", fixedRateCount++) } @ Scheduled (initialDelay = 1000, fixedRate = 5000) / / initialDelay = 1000 means delaying 1000ms execution of * subtask public void testInitialDelay () {logger.info ("= initialDelay: the {} execution method", initialDelayCount++) } @ Scheduled (cron = "0 initialDelay 1 *?") / / cron accepts the cron expression and determines the timing rule public void testCron () {logger.info ("= initialDelay: the {} execution method", cronCount++);}}
We use @ Scheduled to create a timed task this annotation is used to mark a timed task method. By looking at the @ Scheduled source code, we can see that it supports multiple parameters:
(1) cron:cron expression that specifies that the task is executed at a specific time
(2) fixedDelay: indicates how long the last task will be executed again after the completion of the last task. The parameter type is long (in ms).
(3) fixedDelayString: it has the same meaning as fixedDelay, except that the parameter type becomes String
(4) fixedRate: the task is performed at a certain frequency. The parameter type is long (in ms).
(5) fixedRateString: the same meaning as fixedRate, except that the parameter type is changed to String
(6) initialDelay: indicates how long it takes to execute the task * again. Parameter type is long (in ms).
(7) initialDelayString: the same meaning as initialDelay, except that the parameter type is changed to String
(8) zone: time zone, which defaults to the current time zone and is generally not used.
two。 Start a timing task
Import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.scheduling.annotation.EnableScheduling; / * Description: startup class * Designer: jack * Date: 2017-8-10 * Version: 1.0.0 * / @ SpringBootApplication @ EnableScheduling public class Application {public static void main (String [] args) {SpringApplication.run (Application.class, args);}}
Notice the @ EnableScheduling annotation here, which is used to discover the task of the annotation @ Scheduled and perform it in the background. It is impossible to perform scheduled tasks without it.
To quote the original official document:
@ EnableScheduling ensures that a background task executor is created. Without it, nothing gets scheduled.
3. Execution result (single thread)
At this point, we have completed a simple scheduled task model, and let's execute springBoot to observe the execution result.
2017-08-11 12 com.test.ScheduledTasks 06 INFO 19.738 INFO 52252-[com.test.ScheduledTasks] com.test.ScheduledTasks: = initialDelay: first execution method 2017-08-11 12 com.test.ScheduledTasks 06com.test.ScheduledTasks 23.739 INFO 52252-- [pool-1-thread-1] com.test.ScheduledTasks: = fixedRate: second execution method 2017-08-11 12V 0615 23.739 INFO 52252-- -[pool-1-thread-1] com.test.ScheduledTasks: = fixedDelay: second execution method 2017-08-11 12 INFO 06INFO 24.738 INFO 52252-[pool-1-thread-1] com.test.ScheduledTasks: = initialDelay: second execution method 2017-08-11 12 INFO 06INFO 28.739 INFO 52252-[pool-1-thread-1] com.test.ScheduledTasks : = fixedRate: the third execution method 2017-08-11 12 pool-1-thread-1 06 com.test.ScheduledTasks 28.740 INFO 52252-[pool-1-thread-1] com.test.ScheduledTasks: = fixedDelay: the third execution method 2017-08-11 12 Fran 06com.test.ScheduledTasks 29.739 INFO 52252-[pool-1-thread-1] com.test.ScheduledTasks: = = initialDelay: the third time Execution method 2017-08-11 12 com.test.ScheduledTasks 06com.test.ScheduledTasks 33.735 INFO 52252-[pool-1-thread-1] com.test.ScheduledTasks: = fixedRate: fourth execution method 2017-08-11 12 com.test.ScheduledTasks 06com.test.ScheduledTasks 33.741 INFO 52252-- [pool-1-thread-1] com.test.ScheduledTasks: = fixedDelay: fourth execution method 2017-08-11 1206fixedRate 34.738 INFO 52252-[pool-1-thread-1] com.test.ScheduledTasks: = initialDelay: fourth execution method
From the results entered by the console, we can see that all scheduled tasks are handled with the same thread in the same thread pool, so how do we deal with each scheduled task concurrently? please continue to look down.
4. Multithreading processing scheduled tasks
Seeing the output from the console, all the scheduled tasks are handled by a thread. I guess a SingleThreadScheduledExecutor is set in the configuration of the scheduled task, so I look at the source code and look all the way from the ScheduledAnnotationBeanPostProcessor class. Sure enough, there is another judgment in the ScheduleTasks in ScheduledTaskRegistrar (scheduled task registration class):
If (this.taskScheduler = = null) {this.localExecutor = Executors.newSingleThreadScheduledExecutor (); this.taskScheduler = new ConcurrentTaskScheduler (this.localExecutor);}
This means that if taskScheduler is empty, a single-threaded thread pool is made for scheduled tasks, and there happens to be a method to set taskScheduler in this class:
Public void setScheduler (Object scheduler) {Assert.notNull (scheduler, "Scheduler object must not be null"); if (scheduler instanceof TaskScheduler) {this.taskScheduler = (TaskScheduler) scheduler;} else if (scheduler instanceof ScheduledExecutorService) {this.taskScheduler = new ConcurrentTaskScheduler (ScheduledExecutorService) scheduler)) } else {throw new IllegalArgumentException ("Unsupported scheduler type:" + scheduler.getClass ());}}
This problem is very simple, we only need to call this method to explicitly set a ScheduledExecutorService to achieve the effect of concurrency. All we have to do is implement the SchedulingConfigurer interface and rewrite the configureTasks method to OK
Import org.springframework.context.annotation.Configuration; import org.springframework.scheduling.annotation.SchedulingConfigurer; import org.springframework.scheduling.config.ScheduledTaskRegistrar; import java.util.concurrent.Executors; / * Description: multithreaded execution of scheduled tasks * Designer: jack * Date: 2017-8-10 * Version: 1.0.0 * / @ Configuration / / all scheduled tasks are placed in a thread pool, and different threads are used when scheduled tasks are started. Public class ScheduleConfig implements SchedulingConfigurer {@ Override public void configureTasks (ScheduledTaskRegistrar taskRegistrar) {/ / set a 10-length scheduled task thread pool taskRegistrar.setScheduler (Executors.newScheduledThreadPool (10));}}
Note: at first I tried to make an article in the ScheduledAnnotationBeanPostProcessor class because there was a similar method setScheduler (), but * failed. I don't know if I can achieve the concurrency of scheduled tasks through this class. If any, please let me know how to do it.
5. Execution result (concurrent)
2017-08-11 12 com.test.ScheduledTasks 21 INFO 52284-[pool-1-thread-3] com.test.ScheduledTasks: = initialDelay: first execution method 2017-08-11 12 com.test.ScheduledTasks 21 initialDelay 19.998 com.test.ScheduledTasks:-- [pool-1-thread-4] com.test.ScheduledTasks: = fixedRate: second execution method 2017-08-11 12 21 initialDelay INFO 52284-- -[pool-1-thread-1] com.test.ScheduledTasks: = fixedDelay: the second execution method 2017-08-11 12 fixedDelay 21 INFO 20.999 INFO 52284-[pool-1-thread-4] com.test.ScheduledTasks: = initialDelay: the second execution method 2017-08-11 12 Vera 21 fixedDelay 25.000 INFO 52284-[pool-1-thread-2] com.test.ScheduledTasks : = fixedRate: the third execution method 2017-08-11 12 pool-1-thread-6 21 com.test.ScheduledTasks 25.000 INFO 52284-[pool-1-thread-6] com.test.ScheduledTasks: = fixedDelay: the third execution method 2017-08-11 12 pool-1-thread-6 21 com.test.ScheduledTasks 25.997 INFO 52284-[pool-1-thread-3] com.test.ScheduledTasks: = initialDelay: the third time Execution method 2017-08-11 12 fixedRate 21 INFO 30.000 INFO 52284-- [pool-1-thread-7] com.test.ScheduledTasks: = fixedRate: fourth execution method 2017-08-11 12 com.test.ScheduledTasks 21 fixedRate 30.000 INFO 52284-- [pool-1-thread-8] com.test.ScheduledTasks: = fixedDelay: fourth execution method 2017-08-11 12 fixedRate INFO 52284-[pool-1-thread-7] com.test.ScheduledTasks: = initialDelay: fourth execution method
From the results output from the console, we can see that each timing task is handled through a different thread.
III. Detailed explanation of cron
1. Cron expression definition
An Cron expression is a string consisting of six or seven fields separated by spaces, each of which corresponds to a meaning (in seconds, the day, week and year of each month) and its middle age is an optional field.
However, if you click on the blackboard here, the value of spring supports the expression of 6 fields, that is, the year cannot be set, and an error will be reported if there are more than six. The source code is as follows
/ * Parse the given pattern expression. * / private void parse (String expression) throws IllegalArgumentException {String [] fields = StringUtils.tokenizeToStringArray (expression, "); if (! areValidCronFields (fields)) {throw new IllegalArgumentException (String.format (" Cron expression must consist of 6 fields (found% d in\ "% s\"), fields.length, expression);} setNumberHits (this.seconds, fields [0], 0,60) SetNumberHits (this.minutes, fields [1], 0,60); setNumberHits (this.hours, fields [2], 0,24); setDaysOfMonth (this.daysOfMonth, fields [3]); setMonths (this.months, fields [4]); setDays (this.daysOfWeek, replaceOrdinals (fields [5], "SUN,MON,TUE,WED,THU,FRI,SAT"), 8) If (this.daysOfWeek.get (7)) {/ / Sunday can be represented as 0 or 7 this.daysOfWeek.set (0); this.daysOfWeek.clear (7);} private static boolean areValidCronFields (String [] fields) {return (fields! = null & & fields.length = = 6);}
two。 The types of characters that can appear in each field and the meaning of each character
(1) character types supported by each domain
Seconds: can appear ",-* /" four characters, valid range is 0-59 integer
Points: integers with four characters ",-* /" with a valid range of 0-59
When: can appear ",-* /" four characters, valid range is 0-23 integers
The day of the month: an integer with a valid range of 0-31 is available with eight characters ",-* /? L W C".
Month: can appear ",-* /" four characters, valid range is 1-12 integers or JAN-DEc
Week: four characters ",-* /? LC #" can appear, valid range is 1-7 integer or SUN-SAT two ranges. 1 means Sunday, 2 means Monday, and so on
(2) the meaning of special characters
*: it matches any value of the field, such as in seconds *, which means that an event will be triggered every second.
?: can only be used in two domains on the day of the month and the day of the week. Indicates that no value is specified, and when one of the two subexpressions is assigned a value, in order to avoid conflicts, the value of the other subexpression needs to be set to "?"
-: indicates a range, for example, using 5-20 in a sub-domain, indicating that it is triggered every minute from 5 to 20 minutes.
/: indicates that the start time starts to trigger, and then triggers every fixed time. For example, if you use 5 to 20 in the sub-domain, it means 5 points, 25 points, and 45 points, respectively.
Indicates that enumerated values are listed For example, using 5pm 20 in a sub-domain means that it is triggered once at 5 and 20 minutes.
L: represents * *, which can only appear in the week and the day of the month domain. If 1L is used in the week domain, it means that it is triggered on a Sunday of * *.
W: represents a valid business day (Monday to Friday), which can only appear in the domain of the month, and the system will trigger the event on the nearest valid business day from the specified date. Note that W's recent search will not cross the month.
LW: these two characters can be used together to indicate a working day in a month, that is, a Friday.
#: used to determine the day of the month, and can only appear in the domain on the day of the month. For example, on 1: 3, it means the third Sunday of a month.
(3) examples of expressions
Quote the official comments of spring:
*
Example patterns:
*
* "0 0 *" = the top of every hour of every day.
* "* / 10 *" = every ten seconds.
* "0 08-10 *" = 8, 9 and 10 o'clock of every day.
* "00 / 30 8-10 *" = 8:00, 8:30, 9:00, 9:30 and 10 o'clock every day.
* "0 09-17 * * MON-FRI" = on the hour nine-to-five weekdays
* "0 00 25 12?" = every Christmas Day at midnight
"0 *" means that it is executed every hour, 0 minutes and 0 seconds.
"* / 10 *" means to execute every 10 seconds.
"0 08-10 *" means 8 minutes every day, at 9, 10:00.
"00Accord 30 8-10 *" means from 8 to 10:00 every day, every half hour.
"009-17 * * MON-FRI" means that it is executed every Monday to Friday, from 9: 00 to 17:00.
"0 0 25 12?" It is carried out at 00:00:00 on Christmas Day every year.
These are the SpringBoot timing tasks and Cron expressions shared by Xiaobian. If you happen to have similar doubts, you might as well refer to the above analysis to understand. If you want to know more about it, you are welcome to follow the industry information channel.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.