pub fn sleep(duration: Duration) -> Sleep ⓘ展开描述
等待直到 duration 时长过去。
等效于 sleep_until(Instant::now() + duration)。
std::thread::sleep 的异步对应物。
在等待 sleep future 完成时
不执行任何工作。
Sleep
以毫秒粒度运行,
不应用于
需要高分辨率计时器的任务。
该实现是特定于平台的,
某些平台(特别是 Windows)
将提供
分辨率大于 1 毫秒的计时器。
若要按计划定期运行某些东西,
请参阅
interval。
§Cancellation
取消 sleep 实例的方法是丢弃返回的 future。不需要额外的清理工作。
§示例
等待 100 毫秒并打印 "100 毫秒已过"。
use tokio::time::{sleep, Duration};
sleep(Duration::from_millis(100)).await;
println!("100 ms have elapsed");有关更多示例,
请参阅
Sleep 类型的文档。
§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.