Tickers in Squirrel

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 periodically. Here we'll use
        // a Timer and TimerTask to create a similar behavior to Go's ticker.
        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());
            }
        };

        timer.scheduleAtFixedRate(task, 0, 500);

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

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

$ javac Tickers.java
$ 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
Timer stopped

In this Java version, we use java.util.Timer and java.util.TimerTask to create a similar behavior to Go’s ticker. The Timer schedules the TimerTask to run every 500 milliseconds. We use Thread.sleep() to wait for 1600 milliseconds before cancelling the timer. The CountDownLatch is used to signal when the main thread should finish execution, similar to the channel in the Go version.

Note that Java’s Timer continues on a background thread, so we don’t need to create a separate thread as in the Go example. The timer.cancel() method stops the timer from scheduling any more executions of the task.

This example demonstrates how to create periodic tasks in Java, which is a common requirement in many applications for things like updating data, checking for events, or performing regular maintenance tasks.