Interview Questions

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;
    }
}