Tuesday 6 February 2018

Multithreading | Java Timer and TimerTask (A Reminder Class)

java.util.Timer is a utility class that provides the facility for threads to schedule tasks for future execution in a background thread. Tasks may be scheduled for one-time execution, or for repeated execution at regular intervals.

java.util.TimerTask is an abstract class which implements Runnable interface. We need to extend this class to create our own TimerTask which can be scheduled using java Timer class. A task that can be scheduled to run once or for the repeated number of executions. Each timer object is associated with a background thread that is responsible for the execution of all the tasks of timer object.

Run a reminder timer task after a certain time period

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

public class TimerTaskExample {

    Timer timer;

    public TimerTaskExample(int seconds) {
        timer = new Timer();
        long millis = seconds * 1000;
        timer.schedule(new TaskReminder(), millis);
    }

    class TaskReminder extends TimerTask {

        public void run() {
            System.out.println("Timer Task is executing..!");
            /*
             * TimerTask.cancel() method is used to
             * terminate the Time Task.
             */
            timer.cancel();
            System.out.println("Timer Task Finished..!");
        }
    }

    public static void main(String args[]) {
        System.out.println("Timer Task scheduled");
        int reminderTimeSec = 3;
        new TimerTaskExample(reminderTimeSec);
        System.out.println("It will execute after 3 sec...");
    }
}
Output:
Timer Task scheduled
It will execute after 3 sec...
Timer Task is executing..!
Timer Task Finished..!


Perform timer task repeatedly

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


public class RepeatTimerTaskExam {

    Timer timer;
    int nTimes;

    public RepeatTimerTaskExam(long intialDelay, long subsequentRate, int nTimes) {
        timer = new Timer();
        timer.schedule(new TaskReminder(), intialDelay, subsequentRate);

        this.nTimes = nTimes;
    }
   
    /**
     * Class which extending the TimerTask.
     */
    class TaskReminder extends TimerTask {

        public void run() {
            if (nTimes > 0) {
                System.out.println("Timer task, Repeat# " + nTimes);
                nTimes--;
            } else {
                timer.cancel();
                System.out.println("Timer task.. Finished!");
            }
        }
    }

    public static void main(String args[]) {
       
        /** time to start first Task. */
        long intialDelay = 0;

        /** delay subsequent Task. */
        long subsequentRate = 1000;

        new RepeatTimerTaskExam(intialDelay, subsequentRate, 5);
        System.out.println("Task scheduled...");
    }
}
Output:
Task scheduled...
Timer task, Repeat# 5
Timer task, Repeat# 4
Timer task, Repeat# 3
Timer task, Repeat# 2
Timer task, Repeat# 1
Timer task.. Finished!

Few Constructors of Timer
Timer()
Creates a new timer

Timer(boolean isDaemon)
Creates a new timer whose associated thread may be specified to run as a daemon.

Timer(String name)
Creates a new timer whose associated thread has the specified name.

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.

Every class in Java inherit all the methods of the Object class. Methods which inherited from the Object class are:
     clone
     equals
     finalize
     getClass
     hashCode
     notify
     notifyAll
     toString
     wait

Timer class Methods are,
cancel()
java.util.Timer.cancel() Terminates this timer, discarding any currently scheduled tasks. Does not interfere with a currently executing task (if it exists). Once a timer has been terminated, its execution thread terminates gracefully, and no more tasks may be scheduled on it
Syntax:
public void cancel()

purge()
java.util.Timer.purge() Removes all canceled tasks from this timer’s task queue
Syntax:
public int purge()
Returns:
the number of tasks removed from the queue

schedule(TimerTask task, Date time)
java.util.Timer.schedule(TimerTask task, Date time) Schedules the specified task for execution at the specified time
Syntax:
public void schedule(TimerTask task, Date time)
Parameters:
task - task to be scheduled.
time - time at which task is to be executed.
Throws:
IllegalArgumentException - if time.getTime() is negative.
IllegalStateException - if task was already scheduled or canceled,
the timer was canceled, or timer thread terminated.
NullPointerException - if task or time is null

schedule(TimerTask task, Date firstTime, long period)
java.util.Timer.schedule(TimerTask task, Date firstTime, long period) Schedules the specified task for repeated fixed-delay execution, beginning at the specified time
Syntax:
public void schedule(TimerTask task, Date firstTime, long period)
Parameters:
task - task to be scheduled.
firsttime - First time at which task is to be executed.
period - time in milliseconds between successive task executions.
Throws:
IllegalArgumentException - if firstTime.getTime() < 0,
 or period <= 0
IllegalStateException - if task was already scheduled
or cancelled, timer was cancelled,
or timer thread terminated.
NullPointerException - if task or firstTime is null

Deep dive in the Timer
1. Timer class is the thread-safe so multiple threads can share a single Timer object without the need for external synchronization.

2. 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. TaskQueue uses binary heap data structure in order to store its task.

4. Timer class uses Object wait and notify methods to schedule the tasks.

5. Java Timer object can be created to run the associated tasks as a daemon thread. Timer cancel() method is used to terminate the timer and discard any scheduled tasks, however, it doesn’t interfere with the currently executing task and let it finish. If the timer is run as the daemon thread, whether we cancel it or not, it will terminate as soon as all the user threads are finished executing.

6. While scheduling tasks using Timer, you should make sure that time interval is more than normal thread execution, otherwise, tasks queue size will keep growing and eventually task will be executing always.


Related Posts Plugin for WordPress, Blogger...