Wednesday, February 24, 2016

Java Timer and TimerTask Tutorials

java.util.Timer is a utility class that can be used to schedule a thread to be executed at certain time in future. Java Timer class can be used to schedule a task to be run one-time or to be run at regular intervals.
java.util.TimerTask is an abstract class that implements Runnable interface and we need to extend this class to create our own TimerTask that can be scheduled using java Timer class.

Timer class is thread safe and multiple threads can share a single Timer object without need for external synchronization. Timer class uses java.util.TaskQueue to add tasks at given regular interval and at any time there can be only one thread running the TimerTask, for example if you are creating a Timer to run every 10 seconds but single thread execution takes 20 seconds, then Timer object will keep adding tasks to the queue and as soon as one thread is finished, it will notify the queue and another thread will start executing.

Timer class uses Object wait and notify methods to schedule the tasks. TimerTask is an abstract class and we inherit it to provide concrete implementation. TimerTask class implements Runnable interface so it is a thread and hence your implementation of TimerTask is also a thread.

Example to print a repeated task for 5 times.
package com.lea.oops;

import java.util.Timer;
import java.util.TimerTask;

public class TimerTaskExample {

    Timer timer;
   
    public TimerTaskExample() {
        timer = new Timer();
        timer.schedule(new MyReminder(),  0, 1 * 1000);
    }
   
    class MyReminder extends TimerTask{
        int loop = 5;
      
        @Override
        public void run() {
            if (loop > 0) {
                System.out.println("Message "+loop+ "..!\n");
                loop--;
            } else {
                System.out.println("\nThat's it.. Done..!");
                timer.cancel();
            }
           }
      
    }
   
    /**
     * @param args
     */
    public static void main(String[] args) {
        new TimerTaskExample();
        System.out.println("Task scheduled..");
    }

}

No comments: