Asides

Java Tip: How to use Java Timer to synchronize multiple repeating tasks

Recently I had to implement a service that involved multiple nodes in a cluster to aggregate the data for certain period of time and report it back to the central server. The central server, then aggregated results provided by all the nodes in the cluster. This required all the nodes to align properly when reporting the aggregate data to the central.

For example, if the system was configured to aggregate data for 10 minutes, each node in the cluster was expected to send the aggregate data, every 10th minute beginning at the top of the hour. In this case, the central server was expecting data from all the nodes at 10:00 am, 10:10 am, 10:20 am, 10:30 am and so on. The node started at 10:05:15 am was expected to report its aggregate data at 10:10:00 am and every 10th minutes after that (instead of 10 minutes after the node is started and every 10 minutes after that).
The java.util.Timer and java.util.TimerTask utility clases can be very handy to implement such a functionality. These classes can be used to execute tasks periodically or just once. The scheduleAtFixedRate method on the Timer class can be used to delay the task to a specific time.

The following example shows how Timer and TimerTask utilities can be used to implement the functionality explained above.