Tickers in Java

Tickers are used when you want to do something repeatedly at regular intervals. Here’s an example of a ticker that ticks periodically until we stop it.

import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.CountDownLatch;

public class Tickers {
    public static void main(String[] args) throws InterruptedException {
        // Tickers in Java can be implemented using the Timer class
        Timer timer = new Timer();
        CountDownLatch done = new CountDownLatch(1);

        TimerTask task = new TimerTask() {
            @Override
            public void run() {
                System.out.println("Tick at " + new java.util.Date());
            }
        };

        // Schedule the task to run every 500 milliseconds
        timer.scheduleAtFixedRate(task, 0, 500);

        // Tickers can be stopped. Once a ticker is stopped, it won't execute any more tasks.
        // We'll stop ours after 1600ms.
        Thread.sleep(1600);
        timer.cancel();
        System.out.println("Ticker stopped");

        done.countDown();
        done.await();
    }
}

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

$ java Tickers
Tick at Sun Sep 23 11:29:56 PDT 2012
Tick at Sun Sep 23 11:29:56 PDT 2012
Tick at Sun Sep 23 11:29:57 PDT 2012
Ticker stopped

In this Java implementation:

  1. We use the Timer class to schedule a task that repeats at fixed intervals.
  2. The TimerTask is an abstract class that we extend to define the action to be performed at each tick.
  3. We use Thread.sleep() to wait for 1600 milliseconds before stopping the timer.
  4. The CountDownLatch is used to keep the main thread alive until the ticker is stopped.

Note that unlike the original example, Java’s Timer doesn’t provide a channel-like mechanism. Instead, it directly executes the run() method of the TimerTask at each interval.