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.

import java.util.concurrent.*;
import java.time.LocalDateTime;

public class Tickers {
    public static void main(String[] args) throws InterruptedException {
        // Create a ScheduledExecutorService with a single thread
        ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);

        // Schedule a task to run every 500 milliseconds
        ScheduledFuture<?> ticker = scheduler.scheduleAtFixedRate(() -> {
            System.out.println("Tick at " + LocalDateTime.now());
        }, 0, 500, TimeUnit.MILLISECONDS);

        // Let the ticker run for 1600 milliseconds
        Thread.sleep(1600);

        // Stop the ticker
        ticker.cancel(false);
        scheduler.shutdown();
        System.out.println("Ticker stopped");
    }
}

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:

$ javac Tickers.java
$ java Tickers
Tick at 2023-06-10T15:30:00.123
Tick at 2023-06-10T15:30:00.623
Tick at 2023-06-10T15:30:01.123
Ticker stopped

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:

  1. Java uses ScheduledExecutorService instead of Go’s ticker channel.
  2. We schedule a task to run periodically instead of using a select statement with a ticker channel.
  3. Cancellation is done by calling cancel() on the ScheduledFuture returned by scheduleAtFixedRate().

Despite these differences, the core concept of performing a task at regular intervals remains the same.