Timers in D Programming Language

We often want to execute code at some point in the future, or repeatedly at some interval. D’s standard library provides features that make both of these tasks easy. We’ll look first at timers and then at periodic events.

import std.stdio;
import core.thread;
import core.time;

void main()
{
    // Timers represent a single event in the future. You
    // tell the timer how long you want to wait, and it
    // will execute a function after that time. This timer
    // will wait 2 seconds.
    auto timer1 = new Timer({
        writeln("Timer 1 fired");
    }, dur!"seconds"(2));
    timer1.start();

    // The timer.wait() blocks until the timer fires.
    timer1.wait();

    // If you just wanted to wait, you could have used
    // Thread.sleep(). One reason a timer may be useful is
    // that you can stop the timer before it fires.
    // Here's an example of that.
    auto timer2 = new Timer({
        writeln("Timer 2 fired");
    }, dur!"seconds"(1));
    timer2.start();

    // Stop the timer before it has a chance to fire
    timer2.stop();
    writeln("Timer 2 stopped");

    // Give the timer2 enough time to fire, if it ever
    // was going to, to show it is in fact stopped.
    Thread.sleep(dur!"seconds"(2));
}

The first timer will fire ~2s after we start the program, but the second should be stopped before it has a chance to fire.

$ dmd -run timers.d
Timer 1 fired
Timer 2 stopped

In this D version:

  1. We use the core.thread and core.time modules for timer and duration functionality.

  2. Instead of channels, we use D’s Timer class, which takes a delegate (function) to execute when the timer fires.

  3. The Timer.wait() method is used to block until the timer fires, similar to the channel receive in the Go version.

  4. We use Thread.sleep() for the final wait, which is equivalent to time.Sleep() in Go.

  5. The dur!"seconds"(2) syntax is D’s way of creating durations, equivalent to 2 * time.Second in Go.

This example demonstrates basic timer usage in D, including creating, starting, stopping, and waiting for timers.