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.
The first timer will fire ~2s after we start the program, but the second will be “stopped” before it has a chance to fire.
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.