[英]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.