In addition to Weibo, there is also WeChat
Please pay attention

WeChat public account
Shulou
2025-11-06 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)05/31 Report--
This article introduces the relevant knowledge of "how to realize the SpringBoot timing task function". 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!
A background
The project needs a function that can dynamically add timing tasks, and now the project uses the xxl-job timing task scheduling system, but after some understanding of xxl-job functions, it is found that xxl-job can dynamically add timing tasks to the project, and the support for dynamically deleting timing tasks is not so good, so it is necessary to manually implement the function of a timing task.
Two dynamic timing task scheduling
1 Technology selection
Timer or ScheduledExecutorService
Both of them can achieve scheduled task scheduling. Let's take a look at Timer's scheduled task scheduling first.
Public class MyTimerTask extends TimerTask {private String name; public MyTimerTask (String name) {this.name = name;} public String getName () {return name;} public void setName (String name) {this.name = name;} @ Override public void run () {/ / task Calendar instance = Calendar.getInstance () System.out.println (new SimpleDateFormat ("yyyy-MM-dd HH:mm:ss") .format (instance.getTime ());}} Timer timer = new Timer (); MyTimerTask timerTask = new MyTimerTask ("NO.1"); / / first execution, after 1 second of the current time, and then timer.schedule (timerTask,1000L,2000L) every two seconds
Take a look at the implementation of ScheduledThreadPoolExecutor
/ / org.apache.commons.lang3.concurrent.BasicThreadFactoryScheduledExecutorService executorService = new ScheduledThreadPoolExecutor (1, new BasicThreadFactory.Builder () .namingPattern ("example-schedule-pool-%d") .daemon (true) .build (); executorService.scheduleAtFixedRate (new Runnable () {@ Override public void run () {/ / do something}}, initialDelay,period, TimeUnit.HOURS)
Both of them can achieve scheduled tasks, so what's the difference between them? using Ali P3c will give suggestions and differences.
When multithreading processes scheduled tasks in parallel, when Timer runs multiple TimeTask, as long as one of them does not catch the thrown exception, the other tasks will automatically stop running, which is not a problem with ScheduledExecutorService.
From the point of view of the suggestion, we must choose ScheduledExecutorService. Let's look at the source code to see why the execution will be terminated if there is a problem with Timer.
/ * The timer thread. * / private final TimerThread thread = new TimerThread (queue); public Timer () {this ("Timer-" + serialNumber ());} public Timer (String name) {thread.setName (name); thread.start ();}
When we create a new object, we see that a thread is open, so what is the thread doing? Let's take a look.
Class TimerThread extends Thread {boolean newTasksMayBeScheduled = true; / * each task is a quene * / private TaskQueue queue; TimerThread (TaskQueue queue) {this.queue = queue;} public void run () {try {mainLoop ();} finally {/ / Someone killed this Thread, behave as if Timer cancelled synchronized (queue) {newTasksMayBeScheduled = false Queue.clear (); / / clear all task information} / * The main timer loop. (See class comment.) * / private void mainLoop () {while (true) {try {TimerTask task; boolean taskFired; synchronized (queue) {/ / Wait for queue to become non-empty while (queue.isEmpty () & & newTasksMayBeScheduled) queue.wait () If (queue.isEmpty ()) break; / / Queue is empty and will forever remain; die / / Queue nonempty; look at first evt and do the right thing long currentTime, executionTime; task = queue.getMin () Synchronized (task.lock) {if (task.state = = TimerTask.CANCELLED) {queue.removeMin (); continue; / / No action required, poll queue again} currentTime = System.currentTimeMillis (); executionTime = task.nextExecutionTime If (taskFired = (executionTime)
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.

The market share of Chrome browser on the desktop has exceeded 70%, and users are complaining about
The world's first 2nm mobile chip: Samsung Exynos 2600 is ready for mass production.According to a r
A US federal judge has ruled that Google can keep its Chrome browser, but it will be prohibited from
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope





About us Contact us Product review car news thenatureplanet
More Form oMedia: AutoTimes. Bestcoffee. SL News. Jarebook. Coffee Hunters. Sundaily. Modezone. NNB. Coffee. Game News. FrontStreet. GGAMEN
© 2024 shulou.com SLNews company. All rights reserved.