跳到主要内容

timeout

搜索

函数 timeout 

源代码
pub fn timeout<F>(duration: Duration, future: F) -> Timeout<F::IntoFuture> 
where F: IntoFuture,
展开描述

要求 Future 在指定的持续时间过去之前完成。

如果 future 在持续时间过去之前完成,则返回已完成的 future 值。否则,返回错误并取消该 future。

请注意,timeout 是在 poll future 之前检查的,因此如果 future 在执行期间不让步,则 future 可能会完成并超过 timeout,而不会返回错误。

此函数返回一个 future,其返回类型为 Result<T,Elapsed>,其中 T 是所提供 future 的返回类型。

如果所提供的 future 立即完成,则无论提供的持续时间如何,此函数返回的 future 保证立即以 Ok 变体完成。

§Cancellation

取消 timeout 的方法是 drop 该 future。无需进行额外的清理或其他工作。

可以通过调用 Timeout::into_inner 来获取原始 future。这会消费 Timeout

§示例

创建一个设置为在 10 毫秒后到期的新 Timeout

use tokio::time::timeout;
use tokio::sync::oneshot;

use std::time::Duration;

let (tx, rx) = oneshot::channel();

// Wrap the future with a `Timeout` set to expire in 10 milliseconds.
if let Err(_) = timeout(Duration::from_millis(10), rx).await {
    println!("did not receive value within 10 ms");
}

§恐慌

如果未设置当前定时器,此函数会发生 panic。

Builder::enable_timeBuilder::enable_all 未包含在 builder 中时,可能会触发 panic。

每当在 Tokio 运行时之外创建定时器时,它也可能会发生 panic。这就是 rt.block_on(sleep(...)) 会发生 panic 的原因,因为该函数在运行时之外执行。而 rt.block_on(async {sleep(...).await}) 不会 panic,这是因为将函数包装在 async 中使其变为惰性的,从而可以在运行时内成功执行而不会发生 panic。