Menu
Topics Index
...
`


More Utility Classes >
Siva Nookala - 06 Oct 2016
Timer and TimerTask from java.util package are useful for running tasks at specified interval and frequency. They are needed to perform batch updates, cleanups and consolidating the data or actions.

TimerTask is an abstract class with the run method not implemented. Firstly we need to define a task by extending from TimerTask and write the required functionality in the run method. Then we can use the Timer for executing this task at any specified time. A simple example will look like this.
Simple Timer Task Example
import java.util.*;

class SimpleTimerTaskDemo
{
    public static void main(String arg[])
    {
        Timer timer = new Timer();
        MyPrintingTask printingTask = new MyPrintingTask();
        
        int delay = 3000; // THREE SECONDS
        System.out.println("Time Before scheduling : " + new Date());
        timer.schedule(printingTask, delay); // LINE A
        System.out.println("Time After scheduling : " + new Date());
        
        // SLEEP FOR SIX SECONDS, SO THAT THE SCHEDULED TASK IS COMPLETED
        try { Thread.sleep(6000); } catch(Exception e) {}; // LINE B
        timer.cancel();    
    }
}

class MyPrintingTask extends TimerTask
{
    public void run()
    {
        System.out.println("Task executed at : " + new Date());
    }
}
OUTPUT

Time Before scheduling : Sun Dec 28 01:46:44 EST 2014
Time After scheduling : Sun Dec 28 01:46:44 EST 2014
Task executed at : Sun Dec 28 01:46:47 EST 2014

DESCRIPTION

Here we created a custom task called MyPrintingTask which simply prints a line when it is executed. In the main method, we created a Timer and scheduled this printing task with a delay of 3 seconds. Which means, the task will be executed after 3 seconds. If you carefully observe the output, the first two lines are printed in 44th second, where as the task is executed in 47th second.
In normal world we do not need a sleep of 6 seconds in the main method, because we might be performing some other time taking task. We have used this sleep of 6 seconds only to demonstrate how Timer and TimerTask works.

NOTE: The output when you execute will differ since the time would have changed. Only observe the first two lines are printed once, where as the last line is executed after three seconds.

THINGS TO TRY
  • Change the delay from 3 seconds to 5 seconds and see if the output seconds change accordingly.
  • Remove LINE B and observe that the task is not executed, since the main method is complete and timer is cancelled, even before the task is triggered.
  • TRY THIS LOCALLY AFTER DOWNLOADING. Do not call the cancel method on the Timer and see that the program does not return and runs for ever.
There are few other things we need to understand about the Timer class.
TermDescription
isDaemonWhen a timer is marked as isDaemon, it means it will run as daemon and will stop as soon as the main method execution is completed. Otherwise the program will wait until cancel method is called on the Timer object.
Fixed Delay Execution (use the method schedule)In fixed-delay execution, each execution is scheduled relative to the actual execution time of the previous execution. If we start a task with 10 seconds delay and if the first task is started at 5th second and it takes 3 seconds to execute, then the next taks is executed at 5 (last execution time) + 3 (time to execute) + 10 (delay) = 18th second.

We will never have more than one task running at the same time, since the next task is only triggered after the previous task is complete.
Fixed Rate Execution (use the method scheduleAtFixedRate)In fixed-rate execution, each execution is scheduled relative to the scheduled execution time of the initial execution. If we start a task with 10 seconds delay and if the first task is started at 5th second and it takes 3 seconds to execute, then the next task is executed at 5 (last execution time) + 10 (delay) = 15th second.

If the task execution time is longer than the delay, then there are chances that multiple tasks are executed simultaneously.
Mentioned below are various constructors and scheduling methods available in the Timer class.
MethodDescription
public Timer()Constructor for creating the Timer which is not a daemon
public Timer(boolean isDaemon)Constructor for creating the Timer as a daemon
public void schedule(TimerTask task, long delay)Execute a task after the given delay. For e.g., execute printing task after a delay 3000 milli seconds or 3 seconds.
public void schedule(TimerTask task, Date time)Execute a task at the given time. For e.g., execute a task at 15th Dec 2014 9:35 AM.
public void schedule(TimerTask task, long delay, long period)Execute a task multiple times starting after the given delay with a frequency of period. This is fixed-delay execution. Assuming the task takes 3 seconds for executing and the initial delay is 7 seconds and the period is 4, then the task will be executed at 7th, 7+3+4th, 7+3+4+3+4th seconds etc.
public void schedule(TimerTask task, Date firstTime, long period)Execute a task multiple times starting at the given firstTime with a frequency of period. This is fixed-delay execution.
public void scheduleAtFixedRate(TimerTask task, long delay, long period)Same as public void schedule(TimerTask task, long delay, long period), except that it is fixed-rate execution.
public void scheduleAtFixedRate(TimerTask task, Date firstTime, long period)Same as public void schedule(TimerTask task, Date firstTime, long period), except that it is fixed-rate execution.

0
Wrong
Score more than 2 points

© meritcampus 2016 - 2017

All Rights Reserved.