Monday, May 16, 2022

Java Tutorial: Timer and TimerTask

Chapters

Overview

Timer is used to scheule tasks that are provided by TimerTask.In java 1.5 and above, it's preferrable to use ScheduledThreadPoolExecutor class. Java provides an easy-to-use instance of ScheduledThreadPoolExecutor which can be instantiated by invoking newScheduledThreadPool() method.

In java below 1.5, concurrent package was not introduced. Therefore, ScheduledThreadPoolExecutor isn't available in those versions.

Run Timer After a Certain Delay

We can use Timer to perform a task after a certain delay. Take a look at this example.
import java.util.Timer;
import java.util.TimerTask;

public class SampleClass{
  private static final long initTime = 
  System.currentTimeMillis();
  private static volatile boolean endMain = false;
  
  public static void main(String[] args) {
  
    TimerTask myTask = new TimerTask(){
      
      @Override
      public void run(){
        System.out.println("Elapsed Time");
        System.out.println(System.currentTimeMillis() - 
        initTime);
        endMain = true;
      }
    };
    Timer timer = new Timer("MyTimer", true);
    
    System.out.println("Task starts after 2 seconds...");
    long delay = 2000L; //2 seconds
    timer.schedule(myTask, delay);
    
    //block main thread while the scheduled task is not
    //complete yet
    while(!endMain);
    
  }
}

Result(may vary)
Task starts after 2 seconds...
Elapsed Time
2000
First off, TimerTask implements Runnable interface and tasks are run via run() method. Thus, we need to override run() method and write our specified task inside it. Timer(String name, boolean isDaemon) creates a new timer whose associated thread has the specified name, and may be specified to run as a daemon thread.

schedule(TimerTask task, long delay) creates a one-shot schedule for task in TimerTask after a specified delay. Each instance of Timer is associated with a single background thread that executes tasks scheduled by the timer. If you want to set your Timer with a delay based on date & time, use schedule(TimerTask task, Date time).

Schedule Timer with a Fixed Delay or Fixed Rate

If we want to schedule tasks at fixed-delay, we use schedule(TimerTask task, long delay, long period) constructor. for initial delay based on date & time, use schedule(TimerTask task, Date firstTime, long period) constructor. I explained the concepts of fixed delay and fixed rate in this article.

This example demonstrates Timer with fixed-delay.
import java.util.Timer;
import java.util.TimerTask;

public class SampleClass{
  private static final long initTime = 
  System.currentTimeMillis();
  private static volatile boolean endMain = false;
  
  public static void main(String[] args) {
  
    TimerTask myTask = new TimerTask(){
      private int num = 0;
      
      @Override
      public void run(){
        System.out.println("Elapsed Time");
        System.out.println(System.currentTimeMillis() - 
        initTime);
        ++num;
        if(num == 5)
          endMain = true;
      }
    };
    Timer timer = new Timer("MyTimer", true);
    
    System.out.println("Task starts after 2 seconds...");
    long delay = 2000L; //2 seconds
    timer.schedule(myTask, delay, 1000L);
    
    //block main thread while the scheduled task is not
    //complete yet
    while(!endMain);
    
  }
}

Result(may vary)
Elapsed Time
2000
Elapsed Time
3000
Elapsed Time
4000
Elapsed Time
5000
Elapsed Time
6000
If you want to schedule your timer at fixed rate, you can use one of these two methods:
scheduleAtFixedRate(TimerTask task, long delay, long period)
scheduleAtFixedRate(TimerTask task, Date firstTime, long period)

Also, Timer and TimerTask can be cancelled. cancel method in TimerTask cancels all running tasks of this TimerTask and Timer class can't reschedule the task anymore.

cancel method in Timer class cancels the timer. This means that we can't schedule any task in the timer anymore. cancel method in Timer class may not terminate its background thread right after the moment it was cancelled.

No comments:

Post a Comment