跳到主要内容

Module time

搜索

Module time 

源代码
展开描述

用于跟踪时间的实用工具。

此模块提供了多种类型,用于在设定的时间段后执行代码。

  • Sleep 是一个不执行任何工作并在特定 Instant 时刻完成的 future。

  • Interval 是一个以固定周期产生值的流。它使用 Duration 进行初始化,并在每次持续时间过去时重复产生值。

  • 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 每两秒执行一个任务的简单示例。

intervalsleep 之间的区别在于,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 interval and interval_at.
Sleep
Future returned by sleep and sleep_until.
Timeout
Future returned by timeout and timeout_at.

枚举§

MissedTickBehavior
Defines the behavior of an Interval when it misses a tick.

函数§

interval
Creates new Interval that yields with interval of period. The first tick completes immediately. The default MissedTickBehavior is Burst, but this can be configured by calling set_missed_tick_behavior.
interval_at
Creates new Interval that yields with interval of period with the first tick completing at start. The default MissedTickBehavior is Burst, but this can be configured by calling set_missed_tick_behavior.
sleep
Waits until duration has elapsed.
sleep_until
Waits until deadline is reached.
timeout
Requires a Future to complete before the specified duration has elapsed.
timeout_at
Requires a Future to complete before the specified instant in time.