Tickers in D Programming Language

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 std.stdio;
import core.thread;
import core.time;

void main()
{
    // Tickers use a similar mechanism to timers: a
    // channel that is sent values. Here we'll use a
    // shared bool variable to control the loop and
    // a separate thread to simulate the ticker behavior.
    auto ticker = new Thread({
        while (!done)
        {
            Thread.sleep(dur!"msecs"(500));
            if (!done)
                writeln("Tick at ", Clock.currTime());
        }
    });
    
    shared bool done = false;
    ticker.start();

    // Tickers can be stopped. Once a ticker
    // is stopped it won't receive any more values.
    // We'll stop ours after 1600ms.
    Thread.sleep(dur!"msecs"(1600));
    done = true;
    ticker.join();
    writeln("Ticker stopped");
}

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

$ dmd -run tickers.d
Tick at Sat Jun 10 15:30:45 2023
Tick at Sat Jun 10 15:30:46 2023
Tick at Sat Jun 10 15:30:46 2023
Ticker stopped

In this D version, we use a separate thread to simulate the ticker behavior. The shared bool done variable is used to control the loop in the ticker thread. We use Thread.sleep() to pause execution for the specified duration. The Clock.currTime() function is used to get the current time for each tick.

Note that D doesn’t have a built-in ticker mechanism like Go, so we’ve simulated it using a thread and a loop. This approach doesn’t guarantee exactly 500ms between ticks due to the nature of thread scheduling, but it serves to illustrate the concept.