In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article introduces the relevant knowledge of "how to solve the problem of multiple execution of springboot timed task @ Scheduled". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!
Catalogue
The springboot scheduled task @ Scheduled is executed multiple times
Reason
Solution method
Using @ Scheduled to schedule tasks suddenly stops executing
The springboot scheduled task @ Scheduled is executed multiple times
Encountered a very strange phenomenon when developing scheduled tasks in spring boot.. I'm in debug mode, without bug. It took three times to stop.. As shown in the figure:
Reason
Because the execution time is too short, in CronSequenceGenerator.class 's next method.
Public Date next (Date date) {Calendar calendar = new GregorianCalendar (); calendar.setTimeZone (this.timeZone); calendar.setTime (date); / / 1. Set the next execution time to 0 milliseconds. If the last task execution time is less than 1 second, the calendar time will be set to the last task execution time calendar.set (14,0); long originalTimestamp = calendar.getTimeInMillis (); this.doNext (calendar, calendar.get (1)); / / 2. Due to the above step, the execution time is too short, which results in the following condition: true if (calendar.getTimeInMillis () = = originalTimestamp) {/ / 3.calendar adds 1 second calendar.add (13,1) to the original time. / / CronSequenceGenerator's doNext algorithm starts from the specified time (including the specified time) to find the next matching time that conforms to the cron expression rule / / Note that the first match is *. Due to the addition of 1 second, it still conforms to cron= "* 0max 2 *". So the next execution time is to add one second this.doNext (calendar, calendar.get (1)) to the original. } return calendar.getTime ()
The code enters the if statement and sets the execution time to increase by one second from the original.
However, since the timestamp after one second is still consistent with the cron expression, the task starts to execute again a second after the code is executed.
Solution method
It doesn't matter that the execution time of the program is too short, as long as the match of cron expression seconds is not set to *. As shown in the figure:
Using @ Scheduled to schedule tasks suddenly stops executing
In SpringBoot, you can define a scheduled task through the @ Scheduled annotation, but sometimes you may find that some scheduled tasks are not executed when the time is up, but they are not executed every time.
The following code defines a scheduled task that is executed every ten seconds:
@ Componentpublic class ScheduledTaskDemo {private static final Logger logger = LoggerFactory.getLogger (ScheduledTaskDemo.class); @ Scheduled (cron = "0tap 10 *") public void execute () {logger.info ("Scheduled task is running......");}}
When the SpringBoot application is launched, you can see this scheduled task printing a log every 10 seconds on the console.
However, it's not over yet. If there is no relevant log display, check to see if the @ EnableScheduling annotation has been added to the entry class or Configuration class.
In the relevant code above, we use the cron expression to specify the execution time of the scheduled task, that is, starting at 0 seconds and executing every 10 seconds, now let's add another scheduled task:
@ Componentpublic class SecondScheduledTaskDemo {private static final Logger logger = LoggerFactory.getLogger (ScheduledTaskDemo.class); @ Scheduled (cron = "0tap 10 *") public void second () {logger.info ("Second scheduled task is starting......"); logger.info ("Second scheduled task is ending......");}}
Now start the SpringBoot application again, and then take a look at log:
Pay attention to the time point of scheduled task execution in log. The second scheduled task should have been executed every 10 seconds, but from 23:12:20 to 23:13:55, it should have been executed 4 times, but only twice.
Is the cron expression wrong?
No.
To find out why, let's start with the source code of the @ Scheduled annotation:
* *
Processing of {@ code @ Scheduled} annotations is performed by * registering a {@ link ScheduledAnnotationBeanPostProcessor}. This can be * done manually or, more conveniently, through the {@ code} * element or @ {@ link EnableScheduling} annotation. *
To highlight, every method annotated with @ Scheduled is registered as a ScheduledAnnotationBeanPostProcessor, and then move on to ScheduledAnnotationBeanPostProcessor:
/ * Set the {@ link org.springframework.scheduling.TaskScheduler} that will invoke * the scheduled methods, or a {@ link java.util.concurrent.ScheduledExecutorService} * to be wrapped as a TaskScheduler. *
If not specified, default scheduler resolution will apply: searching for a * unique {@ link TaskScheduler} bean in the context, or for a {@ link TaskScheduler} * bean named "taskScheduler" otherwise; the same lookup will also be performed for * a {@ link ScheduledExecutorService} bean. If neither of the two is resolvable, * a local single-threaded default scheduler will be created within the registrar. * @ see # DEFAULT_TASK_SCHEDULER_BEAN_NAME * / public void setScheduler (Object scheduler) {this.scheduler = scheduler;}
Here's the point. Pay attention to this sentence:
This sentence means that if we do not actively configure the TaskScheduler we need, SpringBoot will default to a single-threaded scheduler to handle the scheduled tasks we implemented with the @ Scheduled annotation.
At 23:12:20, the first timed task starts on thread pool-1-thread-1. Because we do not configure scheduler, there is currently only one thread in this thread pool pool-1. After printing the starting log, this thread starts sleep; 's second scheduled task and is ready to execute, but there are no extra threads in the thread pool and can only wait.
At 23:12:30, the first scheduled task is still in sleep and the second scheduled task is still waiting.
At 23:12:35, the first timed task sleep ends, the ending log is printed and ends, the thread pool is idle, the second timed task starts to execute directly from the waiting state, and after the end of execution, the thread pool is idle.
At 23:12:40, the thread pool is idle, the first timed task executes, prints the starting log, and starts sleep.
After figuring out the process, it is very easy to solve the problem.
According to the description of the note just now, we just need to provide a TaskScheduler that meets our needs and register in context.
Configurationpublic class ScheduledTaskConfiguration implements SchedulingConfigurer {/ * * Callback allowing a {@ link TaskScheduler * TaskScheduler} and specific {@ link Task Task} * instances to be registered against the given the {@ link ScheduledTaskRegistrar} * * @ param taskRegistrar the registrar to be configured. * / @ Override public void configureTasks (ScheduledTaskRegistrar taskRegistrar) {final ThreadPoolTaskScheduler taskScheduler = new ThreadPoolTaskScheduler (); taskScheduler.setPoolSize (2); taskScheduler.initialize (); taskRegistrar.setTaskScheduler (taskScheduler);}}
The above code provides a thread pool size of 2 taskScheduler, now start SpringBoot to see the effect.
As you can see, when there are two threads in the thread pool, the two scheduled tasks are triggered at a predetermined time and do not affect each other.
This is the end of the content of "how to solve the problem of multiple execution of springboot scheduled task @ Scheduled". Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!
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.