Sunday, 18 September 2011

Timer on Android

Important: The timer is something that only runs on the lifetime of the application. If you want to timer to continue after the program is dead, use Alarm Manager instead.

Basically the timer is a program which execute a function with a time delay or on a specific date. This execution could be periodic or not.

1. Creating a timer
The easiest way to create a timer is create an empty timer.
private Timer timer = new Timer();

Other constructors could set a name to the timer or set it as daemon. Since this is a simple tutorial, our timer won't have name.

2. Stopping a timer
Once the timer has been initiated, it can be stopped and canceled with the method cancel()

if (timer != null) {
    timer = null;

After the timer has been canceled, it cannot be used any more. No more tasks could be scheduled on this timer. That's why it should be purged, allowing garbage collector to remove it and also set as null.

3. Starting a timer
When the variable timer has been reused, because the previous timer could be canceled and its value is null, it is important start checking the value of the timer.

if (timer == null) {
   timer = new Timer();

To schedule a timer, a timer task could be specified. This timer task is the program which is going to run after specified delay or on a specific date. It runs in another thread. The typic example of the timer task could be:

TimerTask timerTask = new TimerTask() {
    public void run() {
        //Do something

3.1 Not periodic timer.
Those methods could be used to schedule a no specific timer.

3.1.1 After certain delay
timer.schedule(timerTask, scheduledDelay);

Notice that the variable scheduledTime belong to the type Long and it is specified in ms. Here is the code to specify this variable by hours, minutes and seconds:

Long scheduledDelay = new Long(
((((scheduledHour * 60)  +  //scheduledDelay in minutes
scheduledMinutes) * 60) + //scheduledDelay in seconds
scheduledSeconds) * 1000); //scheduledDelay in miliSeconds

3.1.2 On certain Date
The another way to schedule a timer is specifying the date. The type Date in both Android and Java is a bit special. They are described on another post.
The method is:
timer.schedule(timerTask, scheduledDate);

3.2 Periodic timer
It is also possible to specify a period time on Android. In android there are the concept of fixed-delay period and fixed-rate period. Because the simplicity of this tutorial, only the first type will be specified.

3.2.1 After certain delay
The method is similar to the method described in the section 3.1.1

timer.schedule(timerTask, scheduledDelay, period);

Notice the period belongs to the type Long.

3.2.2 On certain Date
The method is similar to the method described in the section 3.1.2

timer.schedule(timerTask, scheduledDate, period);

Notice the period belongs to the type Long.

More information:

No comments:

Post a Comment