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.
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.
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.