pub struct Sleep { /* 私有字段 */ }展开描述
由 sleep 和 sleep_until 返回的 Future。
此类型不实现 Unpin trait,这意味着如果将其与 select! 一起使用或通过调用 poll 来使用,则必须先将其 pin。如果使用 .await,则不适用。
§示例
等待 100 毫秒并打印 “已过 100 毫秒”。
use tokio::time::{sleep, Duration};
sleep(Duration::from_millis(100)).await;
println!("100 ms have elapsed");与 select! 一起使用。当对同一个 Sleep 进行多次选择时,需要使用 tokio::pin! 将其 pin。
use tokio::time::{self, Duration, Instant};
let sleep = time::sleep(Duration::from_millis(10));
tokio::pin!(sleep);
loop {
tokio::select! {
() = &mut sleep => {
println!("timer elapsed");
sleep.as_mut().reset(Instant::now() + Duration::from_millis(50));
},
}
}在带装箱的结构体中使用。通过使用 Box 将 Sleep pin,HasSleep 结构体实现 Unpin,即使 Sleep 没有实现。
use std::future::Future;
use std::pin::Pin;
use std::task::{Context, Poll};
use tokio::time::Sleep;
struct HasSleep {
sleep: Pin<Box<Sleep>>,
}
impl Future for HasSleep {
type Output = ();
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<()> {
self.sleep.as_mut().poll(cx)
}
}在带 pin 投影的结构体中使用。这种方法避免了 Box,但 HasSleep 结构体因此将不实现 Unpin。
use std::future::Future;
use std::pin::Pin;
use std::task::{Context, Poll};
use tokio::time::Sleep;
use pin_project_lite::pin_project;
pin_project! {
struct HasSleep {
#[pin]
sleep: Sleep,
}
}
impl Future for HasSleep {
type Output = ();
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<()> {
self.project().sleep.poll(cx)
}
}实现§
源代码§impl Sleep
impl Sleep
源代码pub fn is_elapsed(&self) -> bool
pub fn is_elapsed(&self) -> bool
如果 Sleep 已过去,则返回 true。
当所请求的持续时间已过去时,Sleep 实例已过去。
源代码pub fn reset(self: Pin<&mut Self>, deadline: Instant)
pub fn reset(self: Pin<&mut Self>, deadline: Instant)
将 Sleep 实例重置为新的截止时间。
调用此函数允许在不创建新的关联状态的情况下,更改 Sleep future 完成的时间点。
此函数可以在 future 完成之前和之后调用。
要调用此方法,通常需要将调用与 Pin::as_mut 结合使用,这样可以调用方法而无需消费 Sleep 本身。
§示例
use tokio::time::{Duration, Instant};
let sleep = tokio::time::sleep(Duration::from_millis(10));
tokio::pin!(sleep);
sleep.as_mut().reset(Instant::now() + Duration::from_millis(20));另请参阅顶级示例。
trait 实现§
自动 trait 实现§
impl !Freeze for Sleep
impl !RefUnwindSafe for Sleep
impl Send for Sleep
impl Sync for Sleep
impl !UnsafeUnpin for Sleep
impl !UnwindSafe for Sleep
blanket 实现§
源代码§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
源代码§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Mutably borrows from an owned value. 更多信息
源代码§impl<F> IntoFuture for Fwhere
F: Future,
impl<F> IntoFuture for Fwhere
F: Future,
源代码§type IntoFuture = F
type IntoFuture = F
我们将要把此值转变成哪种 future?
源代码§fn into_future(self) -> <F as IntoFuture>::IntoFuture
fn into_future(self) -> <F as IntoFuture>::IntoFuture
Creates a future from a value. 更多信息