Tickers in Chapel

Chapel provides a way to create tickers, which are similar to timers but are used for repeatedly performing actions at regular intervals. Here’s an example of a ticker that ticks periodically until we stop it.

use Time;
use IO;

proc main() {
    // Create a new timer that will tick every 500 milliseconds
    var ticker = new Timer();
    ticker.start(500 * 1000, repeat=true);

    // Create a flag to signal when to stop the ticker
    var done = false;

    // Start a task to handle the ticks
    begin {
        while !done {
            ticker.wait();
            if !done {
                writeln("Tick at ", datetime.now());
            }
        }
    }

    // Let the ticker run for 1600 milliseconds
    sleep(1600 * 1000);

    // Stop the ticker
    done = true;
    ticker.clear();
    writeln("Ticker stopped");
}

In this Chapel program, we use the Timer class from the Time module to create a ticker. The timer is set to repeat every 500 milliseconds.

We start a new task using the begin keyword, which is Chapel’s way of creating concurrent execution. This task continuously waits for the timer to tick and prints the current time when it does.

The main thread sleeps for 1600 milliseconds, allowing the ticker to tick approximately three times. After that, we set the done flag to true and clear the timer to stop the ticks.

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

$ chpl tickers.chpl
$ ./tickers
Tick at 2023-06-01T10:30:00.000
Tick at 2023-06-01T10:30:00.500
Tick at 2023-06-01T10:30:01.000
Ticker stopped

Note that the exact times will depend on when you run the program.

Chapel’s approach to tickers is somewhat different from some other languages. Instead of using channels, it provides a Timer class that can be used to create periodic events. The begin keyword is used to create concurrent tasks, which is similar in concept to goroutines in some other languages.