In Java, we use the Timer and TimerTask classes to schedule tasks for future execution. Here’s how the example works:
We create a Timer object and schedule a task to run after 2 seconds using timer1.schedule(). The task is defined as an anonymous inner class extending TimerTask.
We use Thread.sleep() to wait for the first timer to complete. In Java, we need to handle the InterruptedException that sleep() might throw.
For the second timer, we create a separate TimerTask object. This allows us to cancel the task before it fires.
We schedule the second task to run after 1 second, but immediately try to cancel it using task2.cancel().
We sleep for 2 seconds again to give the second timer enough time to fire if it wasn’t successfully cancelled.
Finally, we cancel both timers to clean up resources.
To run this program:
The first timer will fire approximately 2 seconds after we start the program, but the second should be stopped before it has a chance to fire.
Note that Java’s Timer class is older and has some limitations. For more complex scheduling tasks, consider using the ScheduledExecutorService from the java.util.concurrent package, which provides more flexibility and better handles concurrent execution.