Java

Java Thread Timer Usage

In Java, a timer is a class from which timer objects can be instantiated. The timer schedules task for execution in the near future. A task is like a method (function). Java has the class, TimerTask from which task objects can be instantiated. Different tasks are scheduled to operate (execute) at different times. This tutorial explains how to instantiate and use the timer object in Java, beginning with the instantiation of the TimerTask object and its nature.

Article Content

TimerTask

The timerTask object can be seen as a function object. The TimerTask class has to be imported (the java.util.* package). The syntax for instantiation, is:

protected TimerTask()

The reserved word, “protected” means that it can only be defined (implemented) by sub-classing (extends). The following code segment defines a TimerTask class:

class TT extends TimerTask {
        String str;
        TT (String st) {
            str = st;
        }
        public void run() {
System.out.println(str);
        }
     }

The TimerTask class is an abstract class, because it has the abstract method, run() whose syntax is:

public abstract void run()

The run() method must be implemented in the TT class. Here, the TT class is the usable TimerTask class. The run() method is the principal method of the TimerTask class. This run() method is the effective task. In this case, the TT run() method implementation, has just one statement. When the TT class is employed as an object argument, in the Timer object method, the run() method is executed. Instantiation of this TT class is by the expression:

new TT(strObj);

So, in the main() method, the code segment,

TT t1 = new TT("Task 1.");

t1.run();

will print,

Task 1.

Three objects like t1 will be created below for three different tasks for the timer object.

Timer

The timer class has four overloaded constructors, but only one will be considered here. The Timer class is in the java.util.* package. The syntax of the Timer class construction is:

public Timer()

This means that the Timer class will be instantiated with a statement like:

Timer t = new Timer();

Methods of the Timer Class

There are 8 methods of the Timer class. Only four are considered in this article. Three are considered in this section:

schedule(TimerTask task, long delay)

This method schedules a TimerTask object to run after a number of milliseconds (delay). The full syntax is:

public void schedule(TimerTask task, long delay)

cancel()

This method of the Timer terminates the timer, discarding any currently scheduled tasks. The full syntax is:

public void cancel()

purge()

The full syntax is:

public int purge()

This method of the Timer removes all canceled tasks from the timer’s task queue, freeing memory.

Executing Each Task Once

One Timer object can execute (run) more than one TimerTask object. The run() method of the TimerTask object as argument in the schedule method of the Timer object, will run after a delayed time (milliseconds). 1000ms = 1s. The following TT class, shows a good code on how to instantiate TimerTask objects:

import java.util.*;

     class TT extends TimerTask {
        String str; int num; Timer tim;
        TT (String st, int no, Timer timer) {
            str = st; num = no; tim = timer;
        }
        public void run() {
System.out.println(str);
            if (num == 3)
tim.cancel(); tim.purge();
        }
     }

The objects instantiated from the TT class, have associated numbers. In the main() method for this class, there are three TT objects. The constructor for each of these objects, is the constructor for this class. The first parameter to the constructor method is a string. This is the string that the run() method of the object, will print. The second parameter is the number associated with the object. The three instantiated objects from this class have associated numbers from 1 to 3. The next parameter is the timer object. The timer object is instantiated in the main() method. The same timer object will execute each of these three objects, each after a scheduled duration. Each object has a different string (first argument).

It is the last object to be run that will stop the timer. The timer cancel method is used for this. This same last object will purge the timer object. The last TT object, is associated with the number, 3. It is because of all these, that the following code is in the run() method of the TT class:

if (num == 3)
tim.cancel(); tim.purge();

The main class with the main method, is:

    public class TheClass {
        public static void main(String[] args) {
            Timer t = new Timer();
            TT t1 =  new TT("Task 1.", 1, t);
            TT t2 =  new TT("Task 2.", 2, t);
            TT t3 =  new TT("Task 3.", 3, t);

t.schedule(t1, 1000);
t.schedule(t2, 2000);
t.schedule(t3, 3000);
        }
    }

After the Timer object, t has been instantiated from the Timer class, three other objects are instantiated from the TimerTask (TT) class. Note the different arguments of the constructors of these three objects. The first argument is the string to be displayed, that characterizes its object. The next argument is the associated number. The last argument is the Timer object, same for all three objects.

After that in the code, the same timer object runs t1 after 1 second (1000 milliseconds). It runs t2 after 2s. It runs t3 after 3s. Having the object name as the first argument of the timer object schedule method is enough in this situation to cause the run() method of each timer object to execute. After one second, the output is:

Task 1.

and after 1 second again, it is,

Task 2.

and at the fourth second, it is:

Task 3.

Then because of the if-condition and its “tim.cancel();” for the third object, the timer object terminates and the program ends.

Executing Any Task more than Once

A task is a TimerTask inherited (TT) object, whose effectiveness is the run() method. Each TT object can be made to run (execute) repeatedly indefinitely, until a condition is met. The Timer method for this is:

public void schedule(TimerTask task, long delay, long period)

So, each task will execute the first time, after long delay. After a long period (third parameter), it will re-execute; after the same long period (duration), it will re-execute, repeating, until a condition for the timer object is met. In the following code, the first and second tasks (TimerTask objects), are each repeated twice (three occurrences). The third task is executed after its normal delay, once. It has the timer condition that stops the timer (and no repetition).

public class TheClass {
        public static void main(String[] args) {
            Timer t = new Timer();
            TT t1 =  new TT("Task 1.", 1, t);
            TT t2 =  new TT("Task 2.", 2, t);
            TT t3 =  new TT("Task 3.", 3, t);

t.schedule(t1, 1000, 2000);
t.schedule(t2, 2000, 2000);
t.schedule(t3, 6000);
        }
    }

After one second, the output is,

Task 1.

and after the delay of two seconds, from the start, the output is,

Task 2.

after an interval of 2 seconds from when the first task was executed, the output due to the first task is,

Task 1.

and after an interval of 2 seconds from when the second task was executed, the output due to the second task, is,

Task 2.

after an interval of 2 seconds from when the first task was last executed, the output due to the first task is,

Task 1.

and after an interval of 2 seconds from when the second task was last executed, the output due to the second task, is,

Task 2.

After a normal delay of 6 seconds, the output due to the third task, which has the stopping condition, is

Task 3.

Conclusion

The Timer class works with the TimerTask class. The TimerTask class is an abstract class, and so has to be inherited; and its only abstract method, run() must be implemented. From this class (TT above), any number of task objects can be instantiated. As for the Timer class, one object should be instantiated from it. The one timer object can then be used to execute the different TimerTask objects at different times. One of the TimerTask objects should stop the timer object.

Chrys

About the author

Chrysanthus Forcha

Discoverer of mathematics Integration from First Principles and related series. Master’s Degree in Technical Education, specializing in Electronics and Computer Software. BSc Electronics. I also have knowledge and experience at the Master’s level in Computing and Telecommunications. Out of 20,000 writers, I was the 37th best writer at devarticles.com. I have been working in these fields for more than 10 years.