Java timers in applications and animation

Professor Futrelle, Northeastern University, CCIS, Summer 2003

Version of 10 October 2004. Started 1 July 2003

September 2005 - some of the links below need fixing.


Simple knowing the current time in order to compute elapsed times is simple, as this example from the Java Developers Almanac 1.4 shows.

Java has two types of timers both of which are well explained on Sun's website. These are event-based and can be used to control tasks such as animations.

The first note is about java.util.Timer and java.util.TimerTask. Here's a link to it.

The other is about the Swing-based timer, javax.Swing.timer. Here's a link to that discussion. And here's a link to another note "How to Use Swing Timers".

For creating animations, see the example "Creating an Animation Loop with Timer".

Though those are the links to read, below I've put a few tiny pieces of code to demonstrate a bit about how timers work. The first is an example of using a timer to perform a task once per second. Note that on the Sun site this code is presented without the imports and without a main() method to create the task. So beware when you you want to use code snippets! Also note that the RemindTask class is defined internal to the AnnoyingBeep class, something legal in Java. Here's a directory with the source and compiled files.


import java.util.Timer;
import java.util.TimerTask;
import java.awt.Toolkit;

public class AnnoyingBeep {
    Toolkit toolkit;
    Timer timer;

    public AnnoyingBeep() {
	toolkit = Toolkit.getDefaultToolkit();
        timer = new Timer();
        timer.schedule(new RemindTask(),
	               0,        //initial delay
	               1*1000);  //subsequent rate
    }

    class RemindTask extends TimerTask {
	int numWarningBeeps = 3;

        public void run() {
	    if (numWarningBeeps > 0) {
	        toolkit.beep();
		System.out.println("Beep!");
		numWarningBeeps--;
	    } else {
	        toolkit.beep(); 
                System.out.println("Time's up!");
	        //timer.cancel(); //Not necessary because we call System.exit
	        System.exit(0);   //Stops the AWT thread (and everything else)
	    }
        } // run()
    } // class RemindTask
} // class AnnoyingBeep