pub fn timeout<F>(duration: Duration, future: F) -> Timeout<F::IntoFuture> ⓘwhere
F: IntoFuture,展开描述
要求一个 Future 在指定时长过去之前完成。
如果在持续时间过去之前 future 完成, 则返回已完成的 value。否则,返回错误 并且 future 被取消。
请注意, 超时是在轮询 future 之前检查的, 因此如果 future 在执行期间不让出, 则 future 可能会完成 并超出超时 而不会返回错误。
此函数返回一个
future,其返回类型为
Result<T,Elapsed>,
其中 T 是
所提供的 future 的返回类型。
如果所提供的 future 立即完成,
则无论所提供的持续时间如何,
从此函数返回的 future
都保证立即以
Ok 变体完成。
§Cancellation
取消 timeout 的方法是丢弃该 future。不需要额外的清理或其他工作。
可以通过调用
Timeout::into_inner
获取原始 future。
这会消费 Timeout。
§示例
创建一个新的 Timeout,
设置为在 10 毫秒后过期。
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");
}§Panics
如果未设置当前定时器,则此函数会 panic。
当
Builder::enable_time
或
Builder::enable_all
未包含在构建器中时,
可能会触发 panic。
It can also panic whenever a timer is created outside of a
Tokio 运行时。 That is why rt.block_on(sleep(...)) will panic,
since the function is executed outside of the runtime.
Whereas rt.block_on(async {sleep(...).await}) doesn’t panic.
And this is because wrapping the function on an async makes it lazy,
and so gets executed inside the runtime successfully without
panicking.