A timer is an object of Timer class which is the subclass of Object class present in java.lang package. A timer fires one or more action events after regular interval of time (in milliseconds) called delay.
The amount of delay is specified at the time of creation of timer. A timer is used in a program by creating a timer object and invoking start () method. When the timer is started, an event of ActionEvent type is fired and the code enclosed in actionPerformed () of the corresponding listener class is executed. The corresponding class must implement the ActionListener interface. The timer can also be made to fire an event only once by setting its method setRepeats () to false. The methods stop () and restart () can be called to stop or restart the timer, respectively.
The Timer can be created using the following constructor.
Timer(int delay, ActionListener listener)
delay is the time, in milliseconds, between the action events
listener is the action listener
Consider Example. Here, a countdown of 10 seconds is printed. After 10 seconds, the program exits.
Example: A program to demonstrate the use of timer
class TimerExample implements ActionListener
int second = 1;
public static void main(String str)
Timer second= new Timer(1000,this);
public void actionPerformed(ActionEvent e)
if (second == 11)
The output of the program is as shown in Figure