[Switch] Java provides three methods to implement scheduled tasks and java implements three methods.
It is often used in applications to run scheduled tasks in the background. For example, you need to run a scheduled task in the service background for non-real-time computing and clearing temporary data and files. In this article, I will introduce three different implementation methods:
- General thread implementation
- TimerTask implementation
- Implementation of ScheduledExecutorService
Normal thread
This is the most common practice. Create a thread and keep it running in the while loop. The sleep method is used to achieve the effect of scheduled tasks. The Code is as follows:
public class Task1 {public static void main(String[] args) { // run in a second final long timeInterval = 1000; Runnable runnable = new Runnable() { public void run() { while (true) { // ------- code for task to run System.out.println("Hello !!"); // ------- ends here try { Thread.sleep(timeInterval); } catch (InterruptedException e) { e.printStackTrace(); } } } }; Thread thread = new Thread(runnable); thread.start(); }}
Use Timer and TimerTask
The above implementation is very fast and simple, but it also lacks some features.
Using Timer and TimerTask has the following advantages over the above methods:
- It can be controlled when the task is started and canceled
- You can specify the desired delay time for the first task execution.
During implementation, the Timer class can schedule tasks, while the TimerTask class implements specific tasks in the run () method.
A Timer instance can schedule multiple tasks, which are thread-safe.
When the Timer constructor is called, it creates a thread which can be used to schedule tasks:
import java.util.Timer;import java.util.TimerTask;public class Task2 { public static void main(String[] args) { TimerTask task = new TimerTask() { @Override public void run() { // task to run goes here System.out.println("Hello !!!"); } }; Timer timer = new Timer(); long delay = 0; long intevalPeriod = 1 * 1000; // schedules the task to be run in an interval timer.scheduleAtFixedRate(task, delay, intevalPeriod); } // end of main}
ScheduledExecutorService
ScheduledExecutorService is introduced from Java. util. concurrent of java SE 5 as a concurrency tool class, which is the best implementation method for scheduled tasks.
Compared with the above two methods, it has the following benefits:
- Compared with the single thread of Timer, it executes tasks through the thread pool.
- You can flexibly set the delay time for the first task execution.
- Provides good conventions to set the execution Interval
We use ScheduledExecutorService # scheduleAtFixedRate to demonstrate this example. Through the control of parameters in the Code, the first execution adds the delay time:
import java.util.concurrent.Executors;import java.util.concurrent.ScheduledExecutorService;import java.util.concurrent.TimeUnit;public class Task3 { public static void main(String[] args) { Runnable runnable = new Runnable() { public void run() { // task to run goes here System.out.println("Hello !!"); } }; ScheduledExecutorService service = Executors .newSingleThreadScheduledExecutor(); service.scheduleAtFixedRate(runnable, 0, 1, TimeUnit.SECONDS); }}
How to Write scheduled tasks in java
If you want to execute some simple Timer tasks without complicated control or saving the status, you can use the JDK entry-level Timer to execute repetitive tasks.
I. Principles
In JDK, the execution of timer tasks requires two basic classes:
Java. util. Timer;
Java. util. TimerTask;
To run a scheduled task, follow these steps:
1. Create a TimerTask to be executed.
2. Create a Timer instance and add TimerTask to the Timer using the schedule () method provided by Timer. Set the execution rules at the same time.
After the Timer initialization code is executed, the Timer scheduled task is executed according to the settings.
The schedule () method in Timer has multiple reload formats to adapt to different situations. The format of this method is as follows:
Void schedule (TimerTask task, Date time)
Schedule the task to be executed at the specified time.
Void schedule (TimerTask task, Date firstTime, long period)
Schedule the specified task to start repeated fixed delay execution at the specified time.
Void schedule (TimerTask task, long delay)
Schedule the task to be executed after the specified delay.
Void schedule (TimerTask task, long delay, long period)
Schedule the specified task to start repeated fixed delays after the specified delay.
Timer is thread-safe. It can be extended to a large number of tasks simultaneously arranged (there are thousands of tasks with no problems ). All of its constructor Methods start the timer thread. You can call cancel () to terminate this timer and discard all tasks currently scheduled. Purge () removes all canceled tasks from the timer's task queue. This class does not provide real-time guarantee: it uses the Object. wait (long) method to schedule tasks.
TimerTask is an abstract class, which is scheduled by Timer to be executed at one time or repeatedly. It has an abstract method run () ---- the operation to be performed by the timer task. Therefore, each specific task class must inherit the TimerTask class and override the run () method. There are also two non-Abstract METHODS:
Boolean cancel ()
Cancel this timer task.
Long scheduledExecutionTime ()
Returns the scheduled execution time of the task.
Ii. Example
The following is a simple example using Timer:
Package stu. timer;
Import java. util. Date;
Import java. util. TimerTask;
/**
* Repeated tasks
*
* @ Author leizhimin, 9:20:20
*/
Public class TestTimerTask extends TimerTask {
/**
* Operations to be performed by the timer task.
*/
Public void run (){
Date executeTime = new Date (this. scheduledExecutionTime ());
System. out. println ("the execution time of this task is & qu ...... the remaining full text>
Java scheduled execution of a Method
Now we can think of three methods:
1. General thread implementation: This is the most common practice. You can create a thread and keep it running in the while loop. You can use the sleep method to implement scheduled tasks.
2. TimerTask: It can be controlled when the task is started and canceled. You can specify the desired delay time when the task is executed for the first time.
3. Implementation of ScheduledExecutorService: the most ideal implementation method of scheduled tasks. Compared with the single thread of Timer, it executes tasks through the thread pool, you can flexibly set the delay time for the first execution of the task, and provide good conventions to set the execution interval.
Hope to help you.