Three implementations of Java timing tasks

  • 2020-04-01 03:14:54
  • OfStack

Translator's note: in my opinion, it is not a good example to use timed task to run garbage collection. From the perspective of the projects that translators are exposed to, it is common to use timed task to carry out non-real-time calculation and clear temporary data and files.
In this article, I'll introduce you to three different implementations:
1. Common thread implementation
2. The TimerTask implementation
3. ScheduledExecutorService implementation

I. ordinary thread

This is most commonly done by creating a thread and then running it through the while loop through the sleep method to achieve the effect of a timed task. This can be quickly and easily implemented, 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();
  }
}

Second, use Timer and TimerTask

The above implementation is quick and easy, but it also lacks some functionality.
Timer and TimerTask have the following advantages over the above methods:

Control when starting and canceling tasks
2. The first time you execute a task, you can specify the delay time you want

When implemented, the Timer class schedules tasks, while TimerTask implements specific tasks in the run() method.
A Timer instance can schedule multiple tasks and is thread-safe.
When the Timer constructor is invoked, it creates a thread that can be used to schedule tasks.
Here is the code:


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 have existed since JDK 1.3.

Third, ScheduledExecutorService

ScheduledExecutorService was introduced as a concurrent utility class from java.util.concurrent in Java SE 5, which is the ideal way to implement timed tasks.
Compared with the above two methods, it has the following advantages:

1. Compared with the single thread of Timer, it executes the task through thread pool
2. You can set the delay time of the first task flexibly
3. Good conventions are provided to set the execution interval

The following is the implementation code. We show this example through ScheduledExecutorService#scheduleAtFixedRate, with the first execution delayed by the control of the parameters in the code.


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);
  }
}


Related articles: