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

How to build dynamic Management tasks based on Spring Task

2025-01-31 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

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

This article mainly explains "how to build dynamic management tasks based on Spring Task". The content of the explanation is simple and clear, and it is easy to learn and understand. Please follow the editor's ideas to study and learn "how to build dynamic management tasks based on Spring Task".

What is a timed task?

Scheduled tasks refer to the tasks triggered by the scheduler at a specified time or cycle. Common scenarios are as follows:

Send text messages regularly

Timed change data

Timing statistics

Modify the status regularly

Start activities at regular intervals, etc.

Several common ways to implement JAVA

Timer

Introduction: Timer is the timing task execution class of Jdk, no matter any project can directly use Timer to achieve timing tasks, so the advantage of Timer is easy to use.

Principle:

Scheduler: single thread.

Task storage: the minimum heap implements task storage.

Advantages: Jdk comes with classes, does not need to introduce other Jar, easy to use.

Cons: multiple tasks in Timer can only be executed by a single thread, so the execution of tasks will affect each other.

When the execution time of one task is too long, the scheduling task of other tasks will affect other tasks abnormally.

When one task throws an exception, other tasks are also terminated.

Conclusion: almost no one uses it.

ScheduledExecutorService

Introduction: ScheduledExecutorService is one of several thread pools customized in JDK, which supports multi-thread concurrent execution of multiple scheduling tasks, which makes up for the shortcomings of Timer.

Principle:

Scheduler: multithreading.

Task storage: the minimum heap implements task storage.

Pros: Timer can do everything ScheduledExecutorService can do, and it perfectly solves the two problems of Timer mentioned above.

Disadvantages: only support fixed rate (fixed-rate) or fixed delay (fixed-delay) scheduling tasks, not flexible.

Conclusion: it is often used for timing tasks within the framework.

Spring Task

Description: scheduled tasks that come with Spring Framework.

Advantages: same as ScheduledExecutorService, while adding support for cron expressions, you can configure any clock-based scheduling task.

Disadvantages:

Dynamic modification of task status, pausing / resuming tasks, and terminating running tasks are not supported.

Online monitoring of tasks performed is not supported.

Principle: extension of ScheduledExecutorService.

Conclusion: it is often used in small and medium-sized enterprises as a single machine timing task.

The above are all stand-alone versions.

Other distributed timing tasks, such as quartz, xxl-job, elastic-job, etc., have strong features and performance. They are not used as the research object here. For more information, please see:

Comparison of Java timing Task Framework

Timing task realization principle minimum heap time wheel

None of the above frames are what I want to choose. If you want to control lightning freely, you can build a simple wheel to meet 90% of your needs.

Expect to achieve the following features:

Light weight, light weight.

Support online monitoring of tasks performed.

Support for dynamic modification of task status, suspension / resumption of tasks, and termination of running tasks.

Support online configuration and scheduling of task input and participation.

Support for cluster environment extension (optional).

After collecting information for half a day, it can be achieved directly using Spring Task, relying only on Spring Boot.

Spring Task explains entry-level static configuration tasks in detail

Code example:

@ Component @ EnableScheduling / / start timed task public class DemoApplication {/ / add timed task @ Scheduled (cron = "0tick 5 *") / / cron expression, execute public void doTask () {System.out.println ("I am a timed task ~") every 5 seconds;}}

Cannot dynamically modify task status, suspend / resume tasks, and terminate running tasks.

Implementation Design of Advanced dynamic configuration Task

Key technical points and pits

The Spring Task scheduler defaults to ThreadPoolTaskScheduler with a thread count of 1, and the auto-assembly class is TaskSchedulingAutoConfiguration. The execution of multi-tasks will affect each other, so be sure to change the default value.

Through the TaskScheduler interface, you can extend to dynamically modify task status, suspend / resume tasks, and terminate running tasks.

TaskScheuler was introduced in Spring 3.0.There are several ways to run it at some point in the future, and it also returns objects of the ScheduledFuture interface that can be used to cancel scheduled tasks or check whether the task is completed.

Cron-utils a Java library for parsing and verifying Cron expressions, you can go to GitHub to see detailed instructions.

Realization design

Define an IJob interface for client description tasks

Public interface IJob {void execute (JobContext map) throws JobException;}

Definition annotations, used to cooperate with IJob interface definition tasks

@ Target ({ElementType.TYPE}) @ Retention (RetentionPolicy.RUNTIME) @ Documented @ Component public @ interface Job {@ AliasFor (annotation = Component.class) String value () default ""; / * * cron expression does not default to "-" means that * / String cron () default "-"; / * * the task code must be unique * / String taskCode () / * * Task name * / String taskName ();}

Define the status of running tasks

Public class Task {/ * Task Encoding must be globally unique * / private String taskCode; / * * Task name * / private String taskName; / * * Task Class name * / private String taskClassName; / * Task cron expression * / private String taskCron @ JsonIgnore private ScheduledFuture scheduledFuture; @ JsonIgnore private IJob job; private TaskStateEnum taskState

Define a task storage interface for storage in cache or DB

Public interface ITaskStore {void saveTask (Task task); List list (); Task updateTaskByTaskCode (String taskCron, String taskName, String taskCode); Task updateTaskStateByTaskCode (TaskStateEnum taskState, String taskCode); void deleteTaskByTaskCode (String taskCode); Task findByTaskCode (String taskCode);}

Define task lock interfaces, solve concurrency problems, and extend support for cluster environments

Public interface ILockService {void lock (String taskCode); void unlock (String taskCode);}

Define event listeners for listening for task status events, extensible state monitoring, various callbacks, etc.

Public interface IEventListener {void listener (Event event);}

Core processor, handling core processes

Initialize and load all IJob implementations to get IJob implementation classes from the Spring container and parse Job annotations

Add Task threadPoolTaskScheduler.schedule (task,cron)

Update task details

ScheduledFuture.cancel (true)

ThreadPoolTaskScheduler.schedule (task,cron)

Start Task threadPoolTaskScheduler.schedule (task,cron)

Pause task scheduledFuture.cancel (true)

Task monitoring TaskList

Function to be realized

Retry compensation: failed retry.

Failstore: stores failed tasks for human flesh compensation.

Misfire: stores missed tasks for human flesh compensation.

You can add the corresponding enhanced logic to the core processor.

Use the example

You can directly implement the IJob interface and add Job annotations

@ Job (taskCode = "job1", taskName = "laker Test Task", cron = "0 Override public void execute 5 *") @ Slf4j public class TestJob implements IJob {@ Override public void execute (Map map) throws Exception {log.info ("laker job run"); TimeUnit.SECONDS.sleep (10) }} Thank you for reading, the above is the content of "how to build dynamic management tasks based on Spring Task". After the study of this article, I believe you have a deeper understanding of how to build dynamic management tasks based on Spring Task, and the specific use 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