Tickers in Fortress

Our example demonstrates how to use a timer for repeated actions at regular intervals. Here’s an implementation using Java’s ScheduledExecutorService:

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 it run for 1600 milliseconds (should tick 3 times)
        Thread.sleep(1600);

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

In this example, we use ScheduledExecutorService to create a task that runs repeatedly at fixed intervals. Here’s a breakdown of what’s happening:

  1. We create a ScheduledExecutorService with a single thread.

  2. We schedule a task to run every 500 milliseconds using scheduleAtFixedRate(). This method returns a ScheduledFuture object, which we can use to cancel the task later.

  3. The scheduled task simply prints the current time whenever it’s executed.

  4. We let the program run for 1600 milliseconds using Thread.sleep(). This should allow the task to execute about 3 times.

  5. After 1600 milliseconds, we cancel the scheduled task using cancel() on the ScheduledFuture object.

  6. Finally, we shutdown the ScheduledExecutorService and print a message indicating that the ticker has stopped.

When we run this program, the ticker should tick 3 times before we stop it:

$ javac Tickers.java
$ java Tickers
Tick at 2023-06-01T10:15:30.123
Tick at 2023-06-01T10:15:30.623
Tick at 2023-06-01T10:15:31.123
Ticker stopped

This Java implementation provides similar functionality to the original example, using Java’s concurrency utilities to schedule repeated tasks at fixed intervals.