A scheduled task is to execute a program at a specified time, or to execute a scheduled task periodically.
There are many ways to implement timed tasks in Java, mainly some of the methods that come with JDK and open source programs such as Qurtz.
1.Timer 和 TimerTask
Timer just acts as an executor. The real task logic is completed through an abstract class called TimerTask. TimerTask is also a class under the java.util package.
It is an abstract class that implements the Runnable interface and contains an abstract method. The run( ) method requires us to provide specific business implementations ourselves.
The advantage of Timer is its simplicity and ease of use, but since all tasks are scheduled by the same thread,
all tasks are executed serially, and only one task can be executed at the same time, and the delay or exception of the previous task will be will affect subsequent tasks.
Sample code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
|
ScheduledThreadPoolExecutor is recommended after JDK 5.0. A simple understanding of Timer is enough.
2.ScheduledThreadPoolExecutor
ScheduledThreadPoolExecutor belongs to the Executor Framework.
In addition to handling exceptions, it can also execute timed tasks in a multi-threaded manner.
The Timer class executes all TimerTask tasks through a single thread. If the execution of one task is very time-consuming, it will cause problems with the timeliness of other tasks.
The ScheduledThreadPoolExecutor is a multi-threaded execution task based on the thread pool, and there is no such problem.
Learn from an example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
|
3. Use Qurtz
Qurtz is very simple to use and supports more triggering mechanisms as a solution.
具体的应用可以查看官方文档:http://www.quartz-scheduler.org/documentation/quartz-2.2.x/tutorials/