简体   繁体   English

如何在 rust 的可变间隔上运行 function,其中可以从另一个线程更改间隔?

[英]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.我查看了 Tokio 的间隔,但在创建它们后我无法弄清楚如何更改它们。

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.我正在使用的设置是传递持续时间 object 的消息,检索后应该重置间隔,并根据接收到的持续时间开始一个新的间隔。

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?使用如何使用 Tokio 在每个周期或间隔以秒为单位触发 function? as a starting point we can handle two triggers by using tokio::select!作为起点,我们可以使用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 . 操场上的完整演示。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在不使用 Tokio 同时运行相同功能的情况下,以重复间隔同时运行一组函数? - How can I run a set of functions concurrently on a recurring interval without running the same function at the same time using Tokio? 如何在 Rust 2015 中从一个模块到另一个模块进行基本的函数导入/包含? - How do I do a basic import/include of a function from one module to another in Rust 2015? 在Rust中如何将分歧函数作为参数传递给另一个函数 - In Rust how do I pass a diverging function as parameter to another function 如何在 rust 中异步运行另一个 function? - How to run another function as async in rust? 如何使用 Tokio 在每个周期或间隔以秒为单位触发 function? - How can I use Tokio to trigger a function every period or interval in seconds? 如何在 Rust 中从另一个字符中减去一个字符? - How do I subtract one character from another in Rust? 如何将函数发送到另一个线程? - How can I send a function to another thread? 如何从另一个线程终止或挂起 Rust 线​​程? - How to terminate or suspend a Rust thread from another thread? 如何在生成线程时运行 Rust 中的两个函数? - How can I make two functions in Rust run upon spawning a thread? 如何从Rust调用内置的Dyon函数? - How do I call a built-in Dyon function from Rust?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM