Task scheduling refers to the automatic execution of tasks based on a given time point, a given time interval or a given number of executions
1. Preface
Let's take a simple example: create a thread and let it run all the time in the while loop. The sleep method is used to achieve the effect of timed tasks. This can be implemented quickly and simply.
public static void main(String[] args) { final long timeInterval = 1000; Runnable runnable = new Runnable() { public void run() { while (true) { System.out.println("Hello !!"); try { Thread.sleep(timeInterval); } catch (InterruptedException e) { e.printStackTrace(); } } } }; Thread thread = new Thread(runnable); thread.start(); }
However, this consumes system resources, expansibility and does not meet business needs.
2. Task scheduling mode
Timer
ScheduledExecutor
JCronTab
Open Source Toolkit Quartz
1) Timer
I believe everyone is already very familiar with Java util. Timer, which is the simplest method to realize task scheduling
Features: in JDK, concise, single thread
public static void main(String[] args){ Timer timer = new Timer(); timer.schedule(new TimerTask(){ @Override public void run() { System.out.println("do sth..."); } }, 1000, 2000); }
The core classes are Timer and TimerTask
The advantage of Timer is that it is simple and easy to use. However, since all tasks are scheduled by the same thread, all tasks are executed serially. Only one task can be executed at the same time. The delay or exception of the previous task will affect the subsequent tasks.
2) ScheduledExecutor
In view of the above defects of Timer, Java 5 launched a scheduled executor based on thread pool design. The design idea is that each scheduled task will be executed by a thread in the thread pool, so the tasks are executed concurrently and will not be disturbed. It should be noted that only when the execution time of the task comes, the ScheduledExecutor will really start a thread, and the ScheduledExecutor will poll the status of the task for the rest of the time.
package io.renren.modules.job.task; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; /** * @author lanxinghua * @date 2018/08/07 12:45 * @description */ public class ScheduleExecutorTest implements Runnable { private String jobName=""; public ScheduleExecutorTest(String jobName) { this.jobName = jobName; } @Override public void run() { System.out.println("executor "+jobName+Thread.currentThread().getName()); } public static void main(String[] args) { ScheduledExecutorService service = Executors.newScheduledThreadPool(10); ScheduleExecutorTest job1 = new ScheduleExecutorTest("job1"); service.scheduleAtFixedRate(job1,1,1,TimeUnit.SECONDS); service.scheduleAtFixedRate(job1,2,1,TimeUnit.SECONDS); } }
Implementation of complex task scheduling with ScheduledExecutor and Calendar
Timer and ScheduledExecutor can only provide task scheduling based on start time and repetition interval, and are not competent for more complex scheduling requirements. For example, set 16:38:10 every Tuesday to perform tasks. Neither timer nor ScheduledExecutor can directly implement this function, but we can indirectly implement this function with the help of Calendar.
Calculate the interval time, and calculate the time interval from the current time to the latest execution time
long delay = earliestDateLong - currentDateLong; //The calculation execution cycle is one week long period = 7 * 24 * 60 * 60 * 1000; ScheduledExecutorService service = Executors.newScheduledThreadPool(10); //From now on, after delay ing milliseconds, job1 is executed every other week service.scheduleAtFixedRate(test, delay, period, TimeUnit.MILLISECONDS);
It can be seen that it is troublesome to implement the task scheduling with the above method, which requires a more perfect task scheduling framework to solve these complex scheduling problems. Fortunately, the Open Source Toolkit Quartz and JCronTab provide strong support in this regard.
3) JCronTab
Developers accustomed to unix/linux should be familiar with crontab. Crontab is a very convenient task scheduling command for unix/linux systems. JCronTab is a java task scheduling tool written in full accordance with crontab syntax.
Compared with Quartz, JCronTab has the following advantages: first, it supports a variety of persistence methods for task scheduling, including persistence of ordinary files, databases and XML files; Second, JCronTab can be easily combined with Web application server, and task scheduling can be started automatically with the start of Web application server; Third, JCronTab also has a built-in e-mail function, which can easily send the task execution results to the people who need to be notified.
4) Quartz (focus)
Quartz is an open source JAVA library, which can be simply regarded as a combination of the above three extensions.
Scheduler: scheduling container
Job: job interface class
JobDetail: the description class of a job. When a job is executed, it reflects and instantiates the specific execution object of the job according to the information of this object.
Trigger: time policy for storing Job execution
JobStore: stores the status during jobs and scheduling
Calendar: specify the excluded time point (e.g. excluding legal holidays)
There are two main types of threads in Quartz, The thread responsible for scheduling and the thread responsible for Misfire (referring to the job that missed the execution time). The thread responsible for scheduling, RegularSchedulerThread, is based on the thread pool, while Misfire has only one thread. Both types of threads access the layer abstracted as JobStore to obtain the job policy or write the scheduling state. JobStore is also divided into persistent (JobStoreSupport) and non persistent (RAMJobStore) two, with different usage scenarios
Refer to the following information: https://www.w3cschool.cn/quartz_doc/quartz_doc-1xbu2clr.html
https://blog.csdn.net/jiaqingShareing/article/details/81910257