Java provides a number of methods to run code at scheduled future time, the implementations of ScheduledExecutorService generally being the best way at the moment. ScheduledExecutorService also defines methods to run the code a periodic intervals (scheduleAtFixedRate & scheduleWithFixedDelay). However, what if you have classes that need to be notified at regular discrete intervals and need to know which interval that are in. A timer is required that with a set periodicity fires an event on any listeners and passes the number of times the period has elapsed. What this is doing is breaking up continuous “realtime” into discrete blocks or quantums of time. For example, if the period is 10 seconds, at the start the time quantum is 0 until 10 seconds have elapsed and an event is fired denoting the start of the first time quantum. Ten seconds later another event fires as the 2nd time quantum starts, and so on.
This is a fairly simple bit of Java code. Any experienced Java developer has probably already worked out a good solution, but for me it has come up a couple of times in the last few months so I thought I’d write it down.
First, an interface for listeners to the discrete time blocks. Whenever a new time quantum starts this method will be called on any registered listeners.
Then the timer itself. It acts as detailed above. Once started the timer fires an event to it’s listeners with the period specified in the constructor, while keeping a count of how many such events have been fired.