我正在尝试使用 tokio:timer:Timeout
在我的 RPC 请求中引入超时:
use std::time::{Duration, Instant};
use tokio::prelude::*;
use tokio::timer::Delay;
fn main() {
let when = Instant::now() + Duration::from_millis(4000);
let task = Delay::new(when)
.and_then(|_| {
println!("Hello world!");
Ok(())
})
.map_err(|e| panic!("delay errored; err={:?}", e));
let task_with_timeout = task
.timeout(Duration::from_millis(3000))
.map_err(|e| println!("Timeout hit {:?}", e));
let _ = task_with_timeout.wait().expect("Failure");
// tokio::run(task_with_timeout);
}
如果我使用 tokio::run()
运行我的 future_with_timeout
,它会按预期工作。
但是,在 task_with_timeout
上调用 wait 会导致 task
future 出错:
thread 'main' panicked at 'delay errored; err=Error(Shutdown)'
而不是得到
Timeout hit Error(Elapsed)
我不明白使用 tokio::run()
和 wait()
之间的区别。
如何使用 wait
让代码工作?
最佳答案
我不会,也有可能你不能。
阅读timer
模块的文档:
These types must be used from within the context of the
Runtime
or a timer context must be setup explicitly. See the tokio-timer crate for more details on how to setup a timer context.
按照线程,我们到达 tokio_timer::with_default
这需要一个 Tokio 执行器和一个 Timer
。执行者使用 Enter
类型,它本身想要一个 future 来阻止。
所有这一切都表明 Tokio 的 future 可能依赖于纯 executor 之外的功能。如果我正确理解这些术语(很可能我没有理解),这些功能将由 reactor 提供。调用 wait
对此一无所知。
另见:
关于rust - 如何将 tokio::timer::Timeout 与 Future::wait 一起使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57492028/