【发布时间】:2020-03-01 04:49:47
【问题描述】:
我想构建一个程序来收集天气更新并将它们表示为流。我想无限循环调用get_weather(),finish和start之间有60秒的延迟。
简化版如下所示:
async fn get_weather() -> Weather { /* ... */ }
fn get_weather_stream() -> impl futures::Stream<Item = Weather> {
loop {
tokio::timer::delay_for(std::time::Duration::from_secs(60)).await;
let weather = get_weather().await;
yield weather; // This is not supported
// Note: waiting for get_weather() stops the timer and avoids overflows.
}
}
有什么方法可以轻松做到这一点?
当get_weather() 花费超过 60 秒时,使用 tokio::timer::Interval 将不起作用:
fn get_weather_stream() -> impl futures::Stream<Item = Weather> {
tokio::timer::Interval::new_with_delay(std::time::Duration::from_secs(60))
.then(|| get_weather())
}
如果发生这种情况,下一个函数将立即启动。我想在前一个 get_weather() 开始和下一个 get_weather() 开始之间保持 60 秒。
【问题讨论】:
标签: asynchronous rust async-await rust-tokio