In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-29 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article mainly introduces "what is the Spring Schedule Task dynamic rewriting Cron configuration mode". In the daily operation, I believe that many people have doubts about what the Spring Schedule Task dynamic rewriting Cron configuration mode is. The editor consulted all kinds of materials and sorted out simple and easy-to-use operation methods. I hope it will be helpful to answer the doubts of "what is the Spring Schedule Task dynamic rewriting Cron configuration mode?" Next, please follow the editor to study!
Spring Schedule Task dynamically overwrites Cron configuration
You can easily define Scheduled Task using the Spring @ Scheduled tag, but sometimes you need to dynamically overwrite the configuration of Cron in your program.
When will it be?
Well, for example:
The boss thinks the Cron configuration is too ugly and wants to go like this directly: 10:15
General use of Scheduling Tasks
Two tags: @ EnableScheduling, @ Scheduled
@ SpringBootApplication@EnableSchedulingpublic class SchedulingTasksApplication {public static void main (String [] args) {SpringApplication.run (SchedulingTasksApplication.class);}} public class ScheduleTaskSimpleJob {@ Scheduled (cron = "0 15 10 * *?") Public void scheduleCronTask () {long now = System.currentTimeMillis () / 1000; System.out.println ("schedule tasks using cron jobs -" + now);}} can dynamically rewrite CronImplements SchedulingConfigurer and change it as much as you want. Public class ScheduleTaskSimpleJob implements SchedulingConfigurer {public void scheduleCronTask () {long now = System.currentTimeMillis () / 1000; System.out.println ("schedule tasks using cron jobs -" + now);} @ Override public void configureTasks (ScheduledTaskRegistrar taskRegistrar) {taskRegistrar.addTriggerTask (new Runnable () {@ Override public void run () {scheduleCronTask () }, new Trigger () {@ Override public Date nextExecutionTime (TriggerContext triggerContext) {/ / TODO converts the time configuration at 10:15 to cron String cron = "0 15 10 * *?"; CronTrigger trigger = new CronTrigger (cron); Date nextExecDate = trigger.nextExecutionTime (triggerContext); return nextExecDate;}});} @ Scheduled scheduled task dynamically modifies cron parameters
Since version 3. 0, the Spring framework comes with task scheduling capabilities, such as a lightweight Quartz, and it is easy to use and does not need to rely on other JAR packages. Following the consistent style of Spring, the implementation of Spring task scheduling supports both annotation configuration and XML configuration.
Let's talk about the abnormal project requirements: we are working on a data acquisition project for intelligent digital watt-hour meters. The project will eventually be launched in several industrial parks, and each industrial park can customize the data collection cycle of electricity meters. For example, An Industrial Park wants to collect data every 10 minutes, and B Industrial Park wants to collect data every 15 minutes. Because data acquisition is a repetitive periodic task, you can consider using the scheduled task function of the Spring framework.
Normally, it is not easy to modify the execution cycle of scheduled tasks. Stop the service, change the cron parameters of the task, and then restart the service. But is there a possibility that you can dynamically modify the cron parameters of a task while in non-stop service? It's entirely possible!
First, let's take a look at the configuration of tasks that are often specified by Spring.
As follows
Note: when configuring Spring scheduled tasks, you need to add in the xml header of the Spring configuration file.
Add to the "xmlns:task=" http://www.springframework.org/schema/task" and xsi:schemaLocation locations
Http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task.xsd
Then there is the annotated task logic code SpringStaticCronTask.java
Package com.pes_soft.task.demo; import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.context.annotation.Lazy;import org.springframework.scheduling.annotation.Scheduled;import org.springframework.stereotype.Component; @ Lazy (false) @ Componentpublic class SpringStaticCronTask {private static final Logger logger = LoggerFactory.getLogger (SpringStaticCronTask.class); @ Scheduled (cron= "0go 5 *?") Public void staticCronTask () {logger.debug ("staticCronTask is running...");}}
The above tasks are applicable to tasks with a fixed task cycle. If you want to modify the task execution cycle, you can only take the path of "stop service → to modify the task execution cycle → restart service".
Let's take a look at the implementation that can dynamically modify the task cycle while in non-stop service.
The steps are as follows:
Add @ EnableScheduling annotation to the scheduled task class and implement the SchedulingConfigurer interface. (it is worth noting that @ EnableScheduling requires a higher version of Spring. At first, the 3.2.6 version was not successful, but then it was changed to 4.2.5.)
Set a static variable cron, which is used to store the task execution cycle parameters.
Another thread is set up to simulate the external reasons in the actual business to modify the task execution cycle.
Set the task trigger to trigger the task execution, in which you can modify the execution cycle of the task.
The complete SpringDynamicCronTask.java code is as follows:
Package com.pes_soft.task.demo; import java.util.Date; import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.context.annotation.Lazy;import org.springframework.scheduling.Trigger;import org.springframework.scheduling.TriggerContext;import org.springframework.scheduling.annotation.EnableScheduling;import org.springframework.scheduling.annotation.SchedulingConfigurer;import org.springframework.scheduling.config.ScheduledTaskRegistrar;import org.springframework.scheduling.support.CronTrigger;import org.springframework.stereotype.Component @ Lazy (false) @ Component@EnableSchedulingpublic class SpringDynamicCronTask implements SchedulingConfigurer {private static final Logger logger = LoggerFactory.getLogger (SpringDynamicCronTask.class); private static String cron; public SpringDynamicCronTask () {cron = "0go 5 *?"; / / start a new thread to simulate an external change in the task execution cycle new Thread (new Runnable () {@ Override public void run () {try {Thread.sleep (15 * 1000)) } catch (InterruptedException e) {e.printStackTrace ();} cron = "0 take 10 *?"; System.err.println ("cron change to:" + cron);}}) .start () } @ Override public void configureTasks (ScheduledTaskRegistrar taskRegistrar) {taskRegistrar.addTriggerTask (new Runnable () {@ Override public void run () {/ / task logic logger.debug ("dynamicCronTask is running...");}}, new Trigger () {@ Override public Date nextExecutionTime (TriggerContext triggerContext) {/ / task trigger, which can modify the task execution cycle CronTrigger trigger = new CronTrigger (cron) Date nextExec = trigger.nextExecutionTime (triggerContext); return nextExec;});}}
Run demo to check the execution of the task, and you can observe that the execution cycle of the task has changed from 5 seconds to 10 seconds, during which the service has not stopped.
At this point, the study on "what is the dynamic rewriting of Cron configuration by Spring Schedule Task" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!
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.