Periodic Task Scheduling
Before JDK 5.0, java. util. Timer/TimerTask was the only built-in task scheduling method and was very keen to use it for a long time.
Method for periodic task scheduling.
First, we will study the features of Timer/TimerTask (as for javax. swing. Timer, we will not study it anymore ).
Public void schedule (TimerTask task, long delay, long period ){
If (delay <0)
Throw new IllegalArgumentException ("Negative delay .");
If (period <= 0)
Throw new IllegalArgumentException ("Non-positive period .");
Sched (task, System. currentTimeMillis () + delay,-period );
}
Public void scheduleAtFixedRate (TimerTask task, long delay, long period ){
If (delay <0)
Throw new IllegalArgumentException ("Negative delay .");
If (period <= 0)
Throw new IllegalArgumentException ("Non-positive period .");
Sched (task, System. currentTimeMillis () + delay, period );
}
Public class Timer {
Private TaskQueue queue = new TaskQueue ();
/**
* The timer thread.
*/
Private TimerThread thread = new TimerThread (queue );
Java. util. TimerThread. mainLoop ()
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
......
If (! TaskFired) // Task hasnt yet fired; wait
Queue. wait (executionTime-currentTime );
}
If (taskFired) // Task fired; run it, holding no locks
Task. run ();
} Catch (InterruptedException e ){
}
}
}
The above three pieces of code reflect the following features of Timer/TimerTask:
Timer schedules tasks based on absolute time.
All timertasks are executed by only one thread, so only one TimerTask is executed at the same time.
An exception in the execution of any TimerTask will cause Timer to terminate all tasks.
Because it is based on absolute time and executed in a single thread, when multiple tasks are scheduled, a task that has been executed for a long time may lead to a short
A time task is quickly executed multiple times in a short time or multiple tasks are discarded.
Because Timer/TimerTask has these characteristics (defects), this leads to the need for a more comprehensive task scheduling framework to solve these problems.
Problem.
Periodic Task Scheduling
The appearance of java. util. concurrent. ScheduledExecutorService makes up for the defects of Timer/TimerTask.
Public interface ScheduledExecutorService extends ExecutorService {
Public ScheduledFuture <?> Schedule (Runnable command,
Long delay, TimeUnit unit );
Public <V> ScheduledFuture <V> schedule (Callable <V> callable,
Long delay, TimeUnit unit );
Public ScheduledFuture <?> ScheduleAtFixedRate (Runnable command,
Long initialDelay,
Long period,
TimeUnit );
Public ScheduledFuture <?> ScheduleWithFixedDelay (Runnable command,
Long initialDelay,
Long delay,
TimeUnit );
}
First, ScheduledExecutorService is based on ExecutorService and is a complete thread pool scheduling. In addition, the thread pool is added.
API for four scheduling tasks.
Schedule (Runnable command, long delay, TimeUnit unit): one-time start of the task (Runnable) at the specified delay time, no
Return Value.
Schedule (Callable <V> callable, long delay, TimeUnit unit): one-time start of the task (Callable) at the specified delay Time, carrying
A result.
ScheduleAtFixedRate (Runnable command, long initialDelay, long period, TimeUnit unit): Creates and executes
Scheduled operations that are enabled for the first time after the delay have a given cycle; that is, they will be executed after initialDelay and after initialDelay + period, run the command after initialDelay + 2 * period, and so on. If any execution of the task
If an exception occurs, subsequent execution will be canceled. Otherwise, the task can only be terminated by canceling or terminating the program. If
If any execution takes longer than its cycle, subsequent execution will be postponed, but not at the same time.
ScheduleWithFixedDelay (Runnable command, long initialDelay, long delay, TimeUnit unit): Creates and executes
The scheduled operation that is enabled for the first time after the initial delay. Then, there is a given delay between the end of each execution and the start of the next execution. If
If any execution of a task encounters an exception, subsequent execution will be canceled. Otherwise, the task can only be terminated by canceling or terminating the program.
The preceding APIs solve the following problems:
ScheduledExecutorService is scheduled based on relative time.
The Time offset of the thread pool (task queue.
The ScheduledExecutorService Based on the thread pool allows multiple threads to execute tasks at the same time.
Useful.
ScheduledExecutorService Based on the thread pool will exit the execution thread when one of the tasks has an exception, but there will also be a new thread
Add in for execution.
ScheduledExecutorService can prevent tasks from being lost.
The following example shows an example of periodic task scheduling.
Package xylz.study.concurrency.exe cutor;
Import java. util. concurrent. Executors;
Import java. util. concurrent. ScheduledExecutorService;
Import java. util. concurrent. TimeUnit;
Public class ScheduledExecutorServiceDemo {
Public static void main (String [] args) throws Exception {
ScheduledExecutorService execService = Executors. newScheduledThreadPool (3 );
ExecService. scheduleAtFixedRate (new Runnable (){
Public void run (){
System. out. println (Thread. currentThread (). getName () + "->" + System. currentTimeMillis ());
Try {
Thread. sleep (2000L );
} Catch (Exception e ){
E. printStackTrace ();
}
}
}, 1, 1, TimeUnit. SECONDS );
//
ExecService. scheduleWithFixedDelay (new Runnable (){
Public void run (){
System. out. println (Thread. currentThread (). getName () + "->" + System. currentTimeMillis ());
Try {
Thread. sleep (2000L );
} Catch (Exception e ){
E. printStackTrace ();
}
}
}, 1, 1, TimeUnit. SECONDS );
Thread. sleep (5000L );
ExecService. shutdown ();
}
}
Possible output at a time is as follows:
Pool-1-thread-1-> 1294672392657
Pool-1-thread-2-> 1294672392659
Pool-1-thread-1-> 1294672394657
Pool-1-thread-2-> 1294672395659
Pool-1-thread-1-> 1294672396657
In this example, the thread pool of the default three threads is started to schedule two periodic tasks. The first task is executed every 1 second, and the second task
Each task is executed at a fixed interval of 1 second. Each execution time of these two tasks is 2 seconds. The above output has the following conclusions:
The task is executed in multiple threads, and the same task should be executed in the same thread.
ScheduleAtFixedRate indicates that the task is executed at the same time each time. If the task execution time is longer than the cycle, the next task will
Run now. For example, if the execution time is 2 seconds and the cycle time is only 1 second, the interval between the execution of each task is 2 seconds.
ScheduleWithFixedDelay indicates that the start time of the next task is the same as the end time of the previous task. Inbound here every execution
The interval between two tasks is 2 + 1 = 3 seconds.
In fact, the implementation class ScheduledThreadPoolExecutor of ScheduledExecutorService inherits the ThreadPoolExecutor class of the thread pool,
Therefore, it has all the features of the thread pool. But it is also a special thread pool. The number of threads in this thread pool is not limited, and the task queue
Is an unlimited task queue based on DelayQueue. The specific structure and algorithm will be analyzed in subsequent chapters.
Because ScheduledExecutorService has all the features of Timer/TimerTask, it is easier to use, supports concurrency, and is safer,
Therefore, there is no reason to continue using Timer/TimerTask, which can be completely replaced. One thing to note: Construct ScheduledExecutorService
The core thread pool size of the thread pool depends on the number of tasks. Otherwise, resources may be wasted.