In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article introduces the relevant knowledge of "how to dynamically configure execution time in spring schedule". 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!
Spring schedule dynamic configuration execution time
In the past, the time of dynamic modification of scheduled tasks on the saas platform was implemented through a framework such as xx-job, so that we could manage the scheduled tasks of our entire saas platform with a single service, but a small project for the bank recently needed to be localized, so I didn't want to get a lot of services, and they didn't require the modification to take effect immediately. So I directly used spring schedule combined with mysql to dynamically configure the execution time.
The schedule we used before can only use static corn expressions through annotations, SchedulingConfigurer if you want to achieve dynamic, and through the annotation @ EnableScheduling. As follows:
Package com.zqf.marketing.task; import com.zqf.db.marketingrobot.sys.model.RobotSysSwitch;import com.zqf.marketing.sys.service.SwitchService;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.beans.factory.annotation.Autowired;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.Service; import java.util.Date; / * * * @ author zhenghao * @ description * @ date, 2019-1-22 21:50 * / @ Lazy (false) @ Service@EnableSchedulingpublic class TestTaskService implements SchedulingConfigurer {private static Logger log = LoggerFactory.getLogger (TestTaskService.class); @ Autowired private SwitchService switchService; private String SpringDynamicCronTask () {String cron = "0ram 5 *?" / / get the configured corn expression RobotSysSwitch switchById = switchService.getSwitchById (5L); cron = switchById.getSwitchFlag (); log.info (cron); return cron from the database } @ Override public void configureTasks (ScheduledTaskRegistrar scheduledTaskRegistrar) {scheduledTaskRegistrar.addTriggerTask (new Runnable () {@ Override public void run () {/ / task logic log.info ("task_task_tak") }}, new Trigger () {@ Override public Date nextExecutionTime (TriggerContext triggerContext) {String s = SpringDynamicCronTask (); / / Task trigger, which can modify the execution cycle of the task CronTrigger trigger = new CronTrigger (s); Date nextExec = trigger.nextExecutionTime (triggerContext); return nextExec });}}
In this way, we can dynamically modify the execution time of the task, the effective time is, the execution cycle of the last task, can also meet our current needs, so that the internship project can be more flexible!
@ schedule annotations dynamic configuration interval
The dynamic configuration interval is realized by registering the task with the task schedule, and the next scheduling interval is changed each time. If the task is blocked or hung up, it will no longer be scheduled. If the setting time is too long, it will take a long time to wait for the next schedule.
Import org.springframework.beans.factory.annotation.Autowired;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.PeriodicTrigger;import org.springframework.stereotype.Component; import java.util.Date; @ Component@EnableSchedulingpublic class DynamicScheduleTaskSecond implements SchedulingConfigurer {private static final long WEEK_MILLIS = 604800000; private static final long MIN_MILLIS = 1000 Private static long period = 1000; static long l = System.currentTimeMillis (); @ Autowired SetPeriod setPeriod; public static long getPeriod () {return period;} public static void setPeriod (long period) {DynamicScheduleTaskSecond.period = period } @ Override public void configureTasks (ScheduledTaskRegistrar taskRegistrar) {taskRegistrar.addTriggerTask (new Runnable () {@ Override public void run () {try {setPeriod.update (period); System.out.println ("abc"); Long last = System.currentTimeMillis ()-l L = System.currentTimeMillis (); System.out.println (last);} catch (Exception e) {e.printStackTrace ();}, new Trigger () {@ Override public Date nextExecutionTime (TriggerContext triggerContext) {if (period)
< MIN_MILLIS || period >WEEK_MILLIS) period = MIN_MILLIS; PeriodicTrigger periodicTrigger = new PeriodicTrigger (period); Date nextExecDate = periodicTrigger.nextExecutionTime (triggerContext); return nextExecDate;}});}} import org.springframework.stereotype.Component; @ Componentpublic class SetPeriod {private static Long maxPeriod = 1000l; public void update (Long period) {maxPeriod + = 1000 SetScheduleConfig (maxPeriod);} public boolean setScheduleConfig (Long period) {DynamicScheduleTaskSecond.setPeriod (period); return true;}}
The above is a simple example of dynamic scheduling. Let's talk about the basic principles.
The main function of dynamic scheduling is to realize the SchedulingConfigurer functional interface, and the parameters of the method configureTasks in the interface are the key points.
@ FunctionalInterfacepublic interface SchedulingConfigurer {/ * * Callback allowing a {@ link org.springframework.scheduling.TaskScheduler * TaskScheduler} and specific {@ link org.springframework.scheduling.config.Task Task} * instances to be registered against the given the {@ link ScheduledTaskRegistrar}. * @ param taskRegistrar the registrar to be configured. * / void configureTasks (ScheduledTaskRegistrar taskRegistrar);}
By looking at the name ScheduledTaskRegistrar, you can see that it is a scheduling task registration class. Calling the addTriggerTask method of this class requires two parameters.
Public void addTriggerTask (Runnable task, Trigger trigger) {this.addTriggerTask (new TriggerTask (task, trigger));}
One is the task thread, and finally, let's talk about the second Trigger, which is an interface for setting the task trigger time. The specific implementation has two classes, one is the CronTrigger corresponding to the cron type time setting, and the other is the PeriodicTrigger corresponding to the FixDelay and FixRate time settings, which is used in the example.
Public interface Trigger {@ Nullable Date nextExecutionTime (TriggerContext var1);}
The API method parameter is a TriggerContext, which is the context in which the task is triggered, in which the start and end time of the last task and the actual execution time are saved. You need to implement this nextExecutionTime method to return a new Date time based on the last task execution time. New A new periodicTrigger object initializes the period time interval for the new time interval and use the nextExecutionTime method to return a new task scheduling time according to the context time, but the period time can not be too long or too short, it is best to set an interval, so that you can avoid a lot of trouble caused by careless errors, so as to perfectly solve the function of dynamically setting task scheduling interval.
Let's talk about what needs to be done in the first threaded task. The executed task needs to be implemented in other specific classes, then called in this thread, and then the time interval has to be reset according to the time business every time the task is scheduled. For example, change the time interval after reading the configuration, that is, scheduling and specific tasks form a loop, after scheduling and executing specific tasks. Specific tasks are scheduled at intervals.
This is the end of the content of "how to dynamically configure execution time in spring schedule". 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.