0

I've looked at Tokio's intervals, but I can't figure out how to change them after I already create them.

The set-up I'm using is message passing a Duration object, which upon retrieval, should reset the interval, and start a new one based on the received Duration.

Here's an example of the code I'm using so far

fn update() {
    println!("update");
}

pub fn setup_changer(mut rx_dur: Receiver<Duration>) -> Result<()> {
    
    Ok(())
}
Liran
  • 1
  • 2
  • Unfortunately there is nothing we can do to help you if we do not know what you are doing. Please add an code sample to your post. – Locke Dec 01 '22 at 04:21
  • Will do, as soon as I'm near my laptop (in a few hours. – Liran Dec 01 '22 at 05:42
  • Intervals are sequences of instants with fixed timesteps, they are not designed for changeability, if you want that build your own on top of `sleep` with whatever semantics you need (e.g. if you change the time-step to one that's shorter than the time elapsed since the last tick, what's supposed to happen?) – Masklinn Dec 01 '22 at 08:49
  • Isn't sleeping in one thread discouraged? – Liran Dec 01 '22 at 22:23

1 Answers1

0

Using How can I use Tokio to trigger a function every period or interval in seconds? as a starting point we can handle two triggers by using tokio::select!: one for the interval ticking, and one for receiving and updating the duration:

use std::time::Duration;

async fn update() {}

#[tokio::main]
async fn main() {
    let (sender, mut receiver) = tokio::sync::mpsc::unbounded_channel();
    tokio::spawn(async move {
        let mut interval = tokio::time::interval(Duration::from_millis(500));

        loop {
            tokio::select! {
                _ = interval.tick() => {
                    update().await;
                }
                msg = receiver.recv() => {
                    match msg {
                        Some(duration) => { interval = tokio::time::interval(duration); }
                        None => break, // channel has closed
                    }
                }
            }
        }
    });

    // ...
}

Full demo on the playground.

kmdreko
  • 42,554
  • 6
  • 57
  • 106