The three methods for Java to implement scheduled tasks are often used in applications to run scheduled tasks in the background. For example, you need to run a scheduled task in the backend of the service for garbage collection, from the project exposed by the translator, it is common to use scheduled tasks 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
- ScheduledExecutorService implements common 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:
12345678910111213141516171819202122 |
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 that can be used to schedule tasks.
The following code is used:
12345678910111213141516171819 |
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 } |
These classes exist from JDK 1.3.
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: