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
:
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
ScheduledExecutorService
with a single thread.We schedule a task to run every 500 milliseconds using
scheduleAtFixedRate()
. This method returns aScheduledFuture
object, 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 theScheduledFuture
object.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:
This Java implementation provides similar functionality to the original example, using Java’s concurrency utilities to schedule repeated tasks at fixed intervals.