We often want to execute Java code at some point in the future, or repeatedly at some interval. Java’s Timer and TimerTask classes make both of these tasks easy.
In this example, we create two timers. The first timer is set to fire after 2 seconds, and when it does, it prints “Timer 1 fired”. We use Thread.sleep() to block the main thread until the timer fires.
The second timer is set to fire after 1 second, but we cancel it before it has a chance to fire. This demonstrates how you can cancel a timer if you no longer need it.
To run the program, compile and execute it:
The first timer will fire ~2s after we start the program, but the second should be stopped before it has a chance to fire.
Note that in Java, we use Timer and TimerTask classes instead of channels. Also, we need to explicitly cancel the timers at the end to clean up resources, which is not necessary in some other languages with automatic resource management.
Java’s concurrency utilities provide more advanced timing mechanisms, such as ScheduledExecutorService, which might be more appropriate for complex scenarios or when working with thread pools.