Timers in Rust

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

use std::thread;
use std::time::Duration;

fn main() {
    // Timers represent a single event in the future. You
    // tell the timer how long you want to wait, and it
    // will sleep for that duration. This timer will wait 2 seconds.
    let timer1 = thread::spawn(|| {
        thread::sleep(Duration::from_secs(2));
        println!("Timer 1 fired");
    });

    // The join() method blocks until the thread completes.
    timer1.join().unwrap();

    // If you just wanted to wait, you could have used
    // thread::sleep(). One reason a timer may be useful is
    // that you can cancel the timer before it fires.
    // Here's an example of that.
    let timer2 = thread::spawn(|| {
        thread::sleep(Duration::from_secs(1));
        println!("Timer 2 fired");
    });

    // Attempt to stop timer2 by not waiting for it
    println!("Timer 2 stopped");

    // Give timer2 enough time to fire, if it ever
    // was going to, to show it is in fact stopped.
    thread::sleep(Duration::from_secs(2));
}

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

$ cargo run
Timer 1 fired
Timer 2 stopped

In this Rust example, we’re using threads to simulate timers. The thread::spawn function is used to create new threads, and thread::sleep is used to pause execution for a specified duration.

Note that in Rust, there isn’t a direct equivalent to Go’s timer cancellation. In this example, we’re simulating “stopping” the timer by simply not waiting for the thread to complete. In a real-world scenario, you might use channels or atomic flags to signal cancellation to a running thread.

For more complex timing and periodic tasks, you might want to look into crates like tokio which provide more advanced timing capabilities in an asynchronous context.