Tickers in Minitab

Timers are for when you want to do something once in the future - tickers are for 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 use a similar mechanism to timers: a
        // scheduled task that is executed repeatedly. Here we'll use
        // a Timer and TimerTask to achieve similar functionality.
        Timer timer = new Timer();
        CountDownLatch latch = new CountDownLatch(1);

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

        timer.scheduleAtFixedRate(task, 0, 500);

        // Tickers can be stopped like timers. 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");
        latch.countDown();

        latch.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 version, we use a Timer and TimerTask to replicate the functionality of Go’s ticker. The Timer schedules the TimerTask to run every 500 milliseconds. We use a CountDownLatch to keep the main thread alive until we’re done with the ticker.

The Thread.sleep(1600) simulates waiting for 1600 milliseconds before stopping the ticker. After that, we call timer.cancel() to stop the ticker, which is equivalent to ticker.Stop() in the Go version.

Note that Java’s Timer is not as precise as Go’s ticker for short intervals, and for more accurate timing, you might want to consider using ScheduledExecutorService in a real-world application.