setInterval in Rust

Continuing the discussion from Is Rust getting it's message out?:

Most of the complexity comes from the use of abortable from the futures crate. Hopefully this version without cancellation is easier to understand:

fn set_interval<F, Fut>(mut f: F, dur: Duration)
where
    F: Send + 'static + FnMut() -> Fut,
    Fut: Future<Output = ()> + Send + 'static,
{
    // Create stream of intervals.
    let mut interval = time::interval(dur);
    
    tokio::spawn(async move {
        // Skip the first tick at 0ms.
        interval.tick().await;
        loop {
            // Wait until next tick.
            interval.tick().await;
            // Spawn a task for this tick.
            tokio::spawn(f());
        }
    });
}

playground

3 Likes

Any reason for using FnMut closure? The Fn closures work as well. It just felt oddly specific - using FnMut...

Yes. All Fn closures are also FnMut, but there are FnMut closures that are not Fn. For example, a closure that contains an integer and increments it on each call is FnMut, but not Fn.

3 Likes

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.