Java Timer

In this section lets discuss about how to use Timer Api in java.

In many scenarios there may be a need to run a task in repeated time interval. Java
provides a simple api to handle this case using Timer api. The code for executing a Timer task is very simple as follows

Timer t = new Timer();
t.schedule(TimerTask task,long delay,long period);

First create a Timer object then, call its schedule(...) method. Notice that it has three arguments. First argument should be an object of java.util.TimerTask. It is an abstract class which also implements Runnable interface. But the public void run() method is made abstract for the extending class to implement its own custom task.

So once the schedule method is called the run() method in TimerTask object will be executed with a starting delay provided by the second argument and recurring delay of the third argument (long period). Lets see a simple example ( or working code) for timer.

Consider the case of Traffic signals. It changes color from RED -> YELLOW -> GREEN in a fixed time interval. Lets try to simulate the same in this example.

First lets create the traffic signal constants using an Enum class Signal. It has a string constructor argument to set the color. The getValue() method is used to get the current value (or color) of the Signal object. The getSignal(String) method is to retrieve the Signal object for a given color.

Signal class

/**
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS''
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS
 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */

package in.techdive.java.examples.timer;

public enum Signal {
    RED("Red"), YELLOW("Yellow"), GREEN("Green");
    private String value;

    private Signal(String value)
    {
        this.value = value;
    }

    public String getValue()
    {
        return value;
    }

    public Signal getSignal(String value)
    {
        if ("Red".equalsIgnoreCase(value))
            return RED;
        else if ("Yellow".equalsIgnoreCase(value))
            return YELLOW;
        else
            return GREEN;
    }
}

[pagebreak]

Consider the SignalThread class below. It extends from TimerTask and overrides the run() method of Runnable interface. Its constructor takes an argument of enum Signal object and changes its color whenever the run() method is executed.

SignalThread class

/**
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS''
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS
 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */

package in.techdive.java.examples.timer;

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

class SignalThread extends TimerTask
{
    Signal s;

    public SignalThread(Signal s)
    {
        this.s = s;
    }

    @Override
    public void run()
    {
        if (s == Signal.RED)
        {
            s = Signal.YELLOW;
        }
        else if (s == Signal.YELLOW)
        {
            s = Signal.GREEN;
        }
        else
        {
            s = Signal.RED;
        }
        System.out.println(s.getValue());
    }
}

public class SignalSimulator
{
    static final Signal s = Signal.RED;

    public SignalSimulator()
    {
    }

    public static void main(String[] args)
    {
        Signal s = Signal.RED;
        Timer t = new Timer();
        t.schedule(new SignalThread(s), 5000L, 5000);
    }
}

Have a look a the SignalSimulator class above. It is where we schedule the timer task. We have made Signal constant as Signal.RED initially and will be changed based on the recurring timer interval of 5000ms. Also the initial execution delay will be 5000 ms.

[pagebreak]

Lets see how our Traffic Signal Simulator works.

Output:

Yellow
Green
Red
Yellow
Green
Red
Yellow
Green

You can also terminate the timer after a specific period of time using the cancel method in Timer class.

There are also open source API's like quartz which provides a much better way of scheduling in java applications.

Technology: 

Search