【问题标题】:How do I use tokio::timer::Timeout with Future::wait?如何将 tokio::timer::Timeout 与 Future::wait 一起使用?
【发布时间】:2019-08-14 09:34:00
【问题描述】:

我正在尝试使用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 未来出现错误:

thread 'main' panicked at 'delay errored; err=Error(Shutdown)'

而不是得到

Timeout hit Error(Elapsed)

我不明白这里使用tokio::run()wait() 之间的区别。

Playground link

如何使用wait 使代码工作?

【问题讨论】:

    标签: rust rust-tokio


    【解决方案1】:

    我不会,你可能只是不能

    阅读timer 模块的文档:

    这些类型必须在Runtime 的上下文中使用,或者必须明确设置计时器上下文。有关如何设置计时器上下文的更多详细信息,请参阅tokio-timer crate

    按照线程,我们到达tokio_timer::with_default,这需要一个 Tokio 执行器和一个 Timer。执行器使用Enter 类型,它本身想要一个future 来阻止。

    所有这一切都是说 Tokio 的未来可能依赖于纯 executor 之外的功能。如果我正确理解了这些术语(很可能我没有正确理解),那么这些功能是由 reactor 提供的。致电wait 对此一无所知。

    另见:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-29
      • 1970-01-01
      • 2012-12-21
      • 2020-06-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多