展开描述
用于跟踪时间的实用工具。
此模块提供了多种类型,用于在设定的时间段后执行代码。
-
Timeout:包装 future 或流,限制其允许执行的最长时间。如果 future 或流未能在规定时间内完成,则它将被取消并返回错误。
这些类型足以处理涉及时间的大量场景。
这些类型必须在 Runtime 的上下文中使用。
§示例
等待 100ms 并打印"已经过去 100 ms"
use std::time::Duration;
use tokio::time::sleep;
sleep(Duration::from_millis(100)).await;
println!("100 ms have elapsed");要求某个操作不超过 1 秒。
use tokio::time::{timeout, Duration};
async fn long_future() {
// do work here
}
let res = timeout(Duration::from_secs(1), long_future()).await;
if res.is_err() {
println!("operation timed out");
}使用 interval 每两秒执行一个任务的简单示例。
interval 和 sleep 之间的区别在于,interval 度量的是自上一个 tick 以来经过的时间,这意味着如果在两次调用 .tick().await 之间已经过去了一些时间,则 .tick().await 等待的时间可能比为 interval 指定的时间短。
如果将下面示例中的 tick 替换为 sleep,那么该任务将每 3 秒才执行一次,而不是每 2 秒执行一次。
use tokio::time;
async fn task_that_takes_a_second() {
println!("hello");
time::sleep(time::Duration::from_secs(1)).await
}
let mut interval = time::interval(time::Duration::from_secs(2));
for _i in 0..5 {
interval.tick().await;
task_that_takes_a_second().await;
}重新导出§
pub use std::time::Duration;
模块§
- error
- Time error types.
结构体§
- Instant
- A measurement of a monotonically nondecreasing clock.
Opaque and useful only with
Duration. - Interval
- Interval returned by
intervalandinterval_at. - Sleep
- Future returned by
sleepandsleep_until. - Timeout
- Future returned by
timeoutandtimeout_at.
枚举§
- Missed
Tick Behavior - Defines the behavior of an
Intervalwhen it misses a tick.
函数§
- interval
- Creates new
Intervalthat yields with interval ofperiod. The first tick completes immediately. The defaultMissedTickBehaviorisBurst, but this can be configured by callingset_missed_tick_behavior. - interval_
at - Creates new
Intervalthat yields with interval ofperiodwith the first tick completing atstart. The defaultMissedTickBehaviorisBurst, but this can be configured by callingset_missed_tick_behavior. - sleep
- Waits until
durationhas elapsed. - sleep_
until - Waits until
deadlineis reached. - timeout
- Requires a
Futureto complete before the specified duration has elapsed. - timeout_
at - Requires a
Futureto complete before the specified instant in time.