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:
We create a
ScheduledExecutorServicewith a single thread.We schedule a task to run every 500 milliseconds using
scheduleAtFixedRate(). This method returns aScheduledFutureobject, which we can use to cancel the task later.The scheduled task simply prints the current time whenever it’s executed.
We let the program run for 1600 milliseconds using
Thread.sleep(). This should allow the task to execute about 3 times.After 1600 milliseconds, we cancel the scheduled task using
cancel()on theScheduledFutureobject.Finally, we shutdown the
ScheduledExecutorServiceand 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 stoppedThis Java implementation provides similar functionality to the original example, using Java’s concurrency utilities to schedule repeated tasks at fixed intervals.