rust - 如何将 tokio::timer::Timeout 与 Future::wait 一起使用?

标签 rust rust-tokio

我正在尝试使用 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() 之间的区别。

Playground link

如何使用 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/

相关文章:

if-statement - 如何将使用三元运算符的 C++ 代码移植到 Rust?

rust - 为什么编译器说该参数未实现必需的特征?

运行 Rust 应用程序的 Azure 应用服务 Docker 容器发出出站 HTTP 请求 "unable to get local issuer certificate"

rust - 如何在 Rust 中最好地 *fake* 关键字样式函数参数?

rust - rust 安装在其他用户的主目录下如何执行?

rust - 如何通过异步任务获取 tokio_postgres::Client 互斥体的所有权?

rust - (tokio::spawn)借用的值生命周期不长-参数要求 `sleepy`是借用的 `' static`

regex - 如何在正则表达式箱中获取匹配组的索引?

rust - 如何在不阻塞父任务的情况下在另一个任务中生成长时间运行的 Tokio 任务?

rust - 如何查看 TcpStream 并阻塞直到有足够的字节可用?