Tuesday, October 18, 2011

Working with Timers in Java

The Java Timer class is very important and useful when you have to create a real-time application. To create a timer you need specify a task that will be performed when the time conditions are met.

To set the time conditions and the task (which can be implemented using a nested class) you will need to call the schedule or the scheduleAtFixedRate method. You also can set an delay for the timer. The signatures for this methods are:
  • schedule(TimerTask task, Date time)
    • specifies the task and the date of execution for your task. If the date has passed, the task will be executed imediately
  • schedule(TimerTask task, Date firstTime, long period)
    • specifies the task, the date of first execution (also, if the date passed, the task will be executed imediately). The task will be executed repeatedly according to the period (which is specified in milliseconds).
  •  schedule(TimerTask task, long delay)
    • specifies the task and the delay in milliseconds until the task is executed. The task will fire only once.
  •  schedule(TimerTask task, long delay, long period)
    • specifies the task and the delay in milliseconds until the task is executed for the first time. The task will be executed repeatedly according to the period (specified as well in milliseconds).
  •  scheduleAtFixedRate(TimerTask task, Date firstTime, long period)  
    • has the same logic as schedule(TimerTask task, Date firstTime, long period), except it is optimized for tasks that need to respect the time conditions in the long run.
  •  scheduleAtFixedRate(TimerTask task, long delay, long period)
    • has the same logic as schedule(TimerTask task, long delay, long period), except it is optimized for tasks that need to respect the time conditions in the long run.
The main difference between the recurring schedule and scheduleAtFixedRate is that schedule is better for shorter  tasks like repainting a component, changing the text of a label, etc, while scheduleAtFixedRate is when you deal with absolute time (which if different from your application time)

This means that sometimes the execution of your application will be delayed by the garbage collector or some other background activity. The schedule method will not care about this delays and will continue doing the job at its own pace (this is the application time), while the scheduleAtFixedRate will reduce its period to compensate for the "external" delays, so that the absolute timing will be preserved.

So, practically, if you have a task that repeats itself every second for 10 seconds and you will use schedule, the entire execution time may be 12 or 15 seconds according to the external delays. If you use scheduleAtFixedTime, the program execution will always take 10 seconds, even if that means that the task will be repeated 3 times in second to compensate the external delays.

Bellow, I've wrote an example on how to use the Timer class to count 10 seconds and print to console the number of seconds that passed every second.
import java.util.Timer;
import java.util.TimerTask;

public class SecondsCounter 
{
    private static final int SECOND = 1000;
    private int counter, seconds;
    private Timer t1;

    private class CountSecondsTimerTask extends TimerTask
    {
        public void run()
        {
            System.out.println(counter);
            if(counter==seconds)
                SecondsCounter.this.t1.cancel(); //Kill the timer
            counter++;
        }
    }
 
    public SecondsCounter(int seconds)
    {
        this.seconds = seconds;
        this.counter = 0;
        t1 = new Timer(); //Creates new timer
        t1.schedule(new CountSecondsTimerTask(), 0, SECOND); //Schedule timer
    }
}

No comments:

Post a Comment

Got a question regarding something in the article? Leave me a comment and I will get back at you as soon as I can!

Related Posts Plugin for WordPress, Blogger...
Recommended Post Slide Out For Blogger