简体   繁体   中英

How do I run a function on a changeable interval in rust, where the interval can be changed from another thread?

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(())
}

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM