Thursday, July 29, 2010

Repetition in Java: the Timer Class

One of the things computers are best at is doing the same thing over and over again. They can do things over again so fast that it looks like they're doing it all the time. For example, in animating a video game they are reading controls and redrawing the screen so often that it looks like they're doing it constantly.

One tool for making Java do something over and over again is the Timer class.

A Timer can make your program do something on a regular basis, like redraw the screen thirty times a second, or sound a klaxon every two seconds until you go mad.

Here's a simple example of using Timer to print a message to the console once every second:

import java.util.*;

public class TimerTest {
    public static void main(String[] arg){
        Timer tickTock = new Timer();  // Create a Timer object
        TimerTask tickTockTask = new TimerTask(){
           // This is what we want the Timer to do once a second.
            public void run(){
             System.out.println("Tick");
             System.out.println("Tock");
            }
        };

        tickTock.schedule(tickTockTask, 1000, 1000);
    }
}
I've used a shortcut here to override the run() method of the TimerTask. In TimerTask the run() method is abstract, so you create a definition for it for your instance of a TimerTask. Or for a class that extends TimerTask.

In the schedule() method, we set an initial delay time of 1000 milliseconds (one second) and a repeat time of 1000 milliseconds. When run, the program will do what we told it to do in the TimerTask's run() method once every second.

If you use timer in a simple video game, replace the System.out.println() statements in run() with your game loop commands. Then set the schedule() method's repeat rate to whatever you want, for example, use a repeat rate of 33 for about 30 frames per second.

The Timer is not necessarily the best way to do this for all applications, but it's adequate if your demands aren't too great. The Timer makes use of "threads", which is a way of letting a program do more than one thing at a time. For more intensive applications that need an ability to run in a loop, the Thread class and Runnable interface can do more than a simple Timer and TimerTask.