Timers in Java
Java provides built-in timer functionality through the java.util.Timer
and java.util.TimerTask
classes. These allow us to schedule tasks for future execution or repeated execution at fixed intervals. Let’s explore how to use timers in Java.
import java.util.Timer;
import java.util.TimerTask;
public class TimerExample {
public static void main(String[] args) {
// Timers represent a single event in the future. You
// create a TimerTask to define what should happen when
// the timer fires. This timer will wait 2 seconds.
Timer timer1 = new Timer();
timer1.schedule(new TimerTask() {
@Override
public void run() {
System.out.println("Timer 1 fired");
}
}, 2000);
// The main thread will wait for the timer to complete
try {
Thread.sleep(2500);
} catch (InterruptedException e) {
e.printStackTrace();
}
// If you just wanted to wait, you could have used
// Thread.sleep(). One reason a timer may be useful is
// that you can cancel the timer before it fires.
// Here's an example of that.
Timer timer2 = new Timer();
TimerTask task2 = new TimerTask() {
@Override
public void run() {
System.out.println("Timer 2 fired");
}
};
timer2.schedule(task2, 1000);
boolean cancelled = task2.cancel();
if (cancelled) {
System.out.println("Timer 2 cancelled");
}
// Give timer2 enough time to fire, if it ever
// was going to, to show it is in fact cancelled.
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
// Clean up the Timer threads
timer1.cancel();
timer2.cancel();
}
}
The first timer will fire ~2 seconds after we start the program, but the second should be cancelled before it has a chance to fire.
$ javac TimerExample.java
$ java TimerExample
Timer 1 fired
Timer 2 cancelled
In this Java example, we use java.util.Timer
to create timers and java.util.TimerTask
to define the tasks that should be executed when the timers fire. The schedule
method is used to set when the timer should fire.
We use Thread.sleep()
to pause the main thread, allowing time for the timers to fire or to demonstrate that a cancelled timer doesn’t fire.
Note that in Java, we need to explicitly cancel the Timer objects at the end to clean up the timer threads. This is not necessary in languages with garbage collection for threads, but it’s a good practice in Java to prevent potential memory leaks.