Tickers in Mercury
Our example demonstrates the use of periodic timers in Java. While Go has built-in tickers, Java provides similar functionality through the ScheduledExecutorService
class.
In this Java program, we use a ScheduledExecutorService
to create a periodic task that runs every 500 milliseconds. This is similar to the ticker in the original example.
We schedule a task using scheduleAtFixedRate()
, which prints the current time at each tick. The task starts immediately (initial delay of 0) and repeats every 500 milliseconds.
After letting the ticker run for 1600 milliseconds using Thread.sleep()
, we stop it by cancelling the ScheduledFuture
and shutting down the executor service.
When we run this program, the ticker should tick 3 times before we stop it:
This Java implementation provides similar functionality to the original example, using Java’s concurrency utilities to create a periodic task that can be started and stopped.
The main differences are:
- Java uses
ScheduledExecutorService
instead of Go’s ticker channel. - We schedule a task to run periodically instead of using a select statement with a ticker channel.
- Cancellation is done by calling
cancel()
on theScheduledFuture
returned byscheduleAtFixedRate()
.
Despite these differences, the core concept of performing a task at regular intervals remains the same.