Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What is the way for Springboot to dynamically configure Cron parameters with its own timing task?

2025-02-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly explains the "Springboot comes with timing tasks to achieve dynamic configuration of Cron parameters is what", the article explains the content is simple and clear, easy to learn and understand, the following please follow the editor's ideas slowly in-depth, together to study and learn "Springboot comes with timing tasks to achieve dynamic configuration of Cron parameters is what is" it!

Springboot has its own timing task to realize dynamic configuration of Cron parameters

Class, today I would like to share the parameters of SpringBoot dynamic configuration Cron. The scene is like this: the background management interface manages scheduled tasks, dynamically modifies the execution time, then saves it into the database, and queries the time from the database before each task execution to achieve the effect of dynamically modifying Cron parameters. All right, let's see what's going on.

Four implementation methods of SpringBoot timing tasks (main)

Timer: this is the java.util.Timer class that comes with java, which allows you to schedule a java.util.TimerTask task. In this way, you can make your program run at a certain frequency, but not at a specified time. It is generally used less.

ScheduledExecutorService: a class that also comes with jdk; it is a scheduled task class based on thread pool. Each scheduled task is assigned to a thread in the thread pool to execute, that is, tasks are executed concurrently and do not affect each other.

Task, which comes with Spring Task:Spring3.0 later, can be thought of as a lightweight Quartz, and it is much easier to use than Quartz.

Quartz: this is a powerful scheduler that allows your program to be executed at a specified time or at a certain frequency, with a slightly more complex configuration.

1.1 using Timer

This allows you to perform a task at a fixed frequency, not at a specified time.

Public class TestTimer {public static void main (String [] args) {TimerTask timerTask = new TimerTask () {@ Override public void run () {System.out.println ("task run:" + new Date ();}}; Timer timer = new Timer () / / schedule the specified task to be executed with a repetitive fixed delay at the specified time. Here, timer.schedule (timerTask,10,3000) is executed every 3 seconds;}}

1.2 using ScheduledExecutorService is similar to timer

Public class TestScheduledExecutorService {public static void main (String [] args) {ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor (); / / parameters: 1, task body 2, delay time / / 3 for the first execution, task execution interval 4, interval time unit service.scheduleAtFixedRate (()-> System.out.println ("task ScheduledExecutorService" + new Date ()), 0,3, TimeUnit.SECONDS);}}

1.3Use Spring Task

We mainly explain the use of its dynamic configuration.

At the beginning of use, we change the execution time of a task, which usually goes like this: modify the execution cycle of a scheduled task, stop the service, change the cron parameters of the task, and then restart the service. This method is very simple, there is nothing to say, but is there a possibility, in the case of non-stop service, you can dynamically modify the cron parameters of the task? Yes, there must be!

In the method just mentioned, we annotate the main class with @ EnableScheduling and the task method with @ Scheduled (cron = "0bind 5 *") to define the execution time, but the steps for dynamic configuration are a little different:

1. Add @ EnabledScheduling annotation to the scheduled task class and implement the SchedulingConfigurer interface.

two。 Set a static cron to store the task execution cycle parameters.

3. Get the Cron parameter from the database, which is used to simulate the external reasons in the actual business to modify the task execution cycle.

4. Set up task triggers to trigger task execution.

Import java.util.Date;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;import java.time.LocalDateTime;@Component @ EnableSchedulingpublic class TaskCronChange implements SchedulingConfigurer {public static String cron @ Override public void configureTasks (ScheduledTaskRegistrar taskRegistrar) {/ / when the project is deployed, it will be executed here once, getting the cron expression cron = timerQueryMapper.getCronTime (); Runnable task = new Runnable () {@ Override public void run () {/ / task logic code section from the database. System.out.println ("I am going:" + LocalDateTime.now ());}}; Trigger trigger = new Trigger () {@ Override public Date nextExecutionTime (TriggerContext triggerContext) {/ / task trigger, which can modify the execution cycle of the task. / / each time a task is triggered, the method here will be executed once to retrieve the next execution time cron = timerQueryMapper.getCronTime (); CronTrigger trigger = new CronTrigger (cron); Date nextExec = trigger.nextExecutionTime (triggerContext); return nextExec;}}; taskRegistrar.addTriggerTask (task, trigger);}}

Because the cron expression of the time is not modified until the task is executed once, the change to cron will not take effect until the next task is executed.

The core here is the use of ScheduledTaskRegistrar this class has a method addTriggerTask (Runnable,Trigger) with two parameters, one Runnable, one is Trigger, executes the business logic code in Runnable, and modifies the execution cycle of scheduled tasks in Trigger.

1.4 Integration of Quartz

If the SpringBoot version is after 2.0.0, then the quart dependency is already included in the spring-boot-starter, so you can use the spring-boot-starter-quartz dependency directly. If it is less than 2.0.0, you need to add additional quartz dependencies.

Spring dynamically configures cron expressions without service outage

There are two common ways for spring to schedule scheduled tasks, which are profile-based quartz and annotation-based @ Scheduler.

Quartz needs more configuration files, which is troublesome for me. The @ Scheduler annotation only requires simple configuration. However, these two methods cannot dynamically load cron expressions, and the service needs to be restarted every time the scheduling rules are changed.

This article introduces a method of dynamically loading cron expressions without restarting the service.

Implementation of dynamic loading cron expression with SchedulingConfigurer interface

The code example is as follows:

@ Component@EnableSchedulingpublic class Test implements SchedulingConfigurer {@ Override public void configureTasks (ScheduledTaskRegistrar scheduledTaskRegistrar) {/ / create a thread pool scheduler. By default, single-thread execution ScheduledExecutorService executorService = Executors.newScheduledThreadPool; scheduledTaskRegistrar.setScheduler (executorService); / / add task scheduledTaskRegistrar.addTriggerTask (new Task ("test1"), new Trig ("cronExpess1")) ScheduledTaskRegistrar.addTriggerTask (new Task ("test2"), new Trig ("cronExpess2"); scheduledTaskRegistrar.addTriggerTask (new Task ("test3"), new Trig ("cronExpess2"));}} / * Business Class * / class Task implements Runnable {String task; public Task (String task) {this.task = task } / / specific business @ Override public void run () {System.out.println (task+ ":" + LocalDateTime.now () + "," + Thread.currentThread () .getName ());}} / * scheduling class * / class Trig implements Trigger {private String cronExpress; public Trig (String cronExpress) {this.cronExpress = cronExpress;} @ Override public Date nextExecutionTime (TriggerContext triggerContext) {String cron = null Try {/ / load cron expression cron = new Config (). GetCrons (). Get (cronExpress);} catch (IOException e) {e.printStackTrace ();} CronTrigger cronTrigger = new CronTrigger (cron); return cronTrigger.nextExecutionTime (triggerContext);}} / * * load cron expression * / class Config {private static Map cronMap Private static long preModifyTime; private String cronFile = "config/application.properties"; public Map getCrons () throws IOException {File file = new File (cronFile); long nowModifyTime = file.lastModified (); if (cronMap! = null & & nowModifyTime = = preModifyTime) {return cronMap;} else {cronMap = new HashMap (); BufferedReader br = new BufferedReader (new FileReader (file)) String line = null; while ((line = br.readLine ())! = null) {String [] s = line.split ("="); cronMap.put (s [0] .trim (), s [1] .trim ());} preModifyTime = nowModifyTime; return cronMap;}}

Configuration file:

CronExpess1 = 0tic5 * cronExpess2 = 0lap10 *

Run the results (only one task is run for ease of viewing):

Thank you for your reading, the above is the content of "Springboot comes with timing tasks to achieve dynamic configuration of Cron parameters". After the study of this article, I believe you have a deeper understanding of what is the way to dynamically configure Cron parameters with scheduled tasks in Springboot. The specific use of the situation also needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

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.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report