[英]How can I run a set of functions concurrently on a recurring interval without running the same function at the same time using Tokio?
[英]How do I run a function on a changeable interval in rust, where the interval can be changed from another thread?
我查看了 Tokio 的間隔,但在創建它們后我無法弄清楚如何更改它們。
我正在使用的設置是傳遞持續時間 object 的消息,檢索后應該重置間隔,並根據接收到的持續時間開始一個新的間隔。
這是我目前使用的代碼示例
fn update() {
println!("update");
}
pub fn setup_changer(mut rx_dur: Receiver<Duration>) -> Result<()> {
Ok(())
}
使用如何使用 Tokio 在每個周期或間隔以秒為單位觸發 function? 作為起點,我們可以使用tokio::select!
:一個用於間隔滴答,一個用於接收和更新持續時間:
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
}
}
}
}
});
// ...
}
操場上的完整演示。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.