pub struct Sleep { /* private fields */ }展开描述
由 sleep 和 sleep_until 返回的 Future。
此类型未实现 Unpin trait,这意味着如果将其与 select! 一起使用或通过调用 poll,则必须先将其 pin。如果使用 .await,则不存在此问题。
§示例
等待 100ms 并输出“已过去 100ms”。
use tokio::time::{sleep, Duration};
sleep(Duration::from_millis(100)).await;
println!("100 ms have elapsed");Use with select!. Pinning the Sleep with tokio::pin! is
necessary when the same Sleep is selected on multiple times.
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));
},
}
}Use in a struct with boxing. By pinning the Sleep with a Box, the
HasSleep struct implements Unpin, even though Sleep does not.
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)
}
}Use in a struct with pin projection. This method avoids the Box, but
the HasSleep struct will not be Unpin as a consequence.
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)
}
}实现§
Source§impl Sleep
impl Sleep
Sourcepub fn is_elapsed(&self) -> bool
pub fn is_elapsed(&self) -> bool
如果 Sleep 已过期,则返回 true。
当所请求的时长已过去时,Sleep 实例处于已过期状态。
Sourcepub fn reset(self: Pin<&mut Self>, deadline: Instant)
pub fn reset(self: Pin<&mut Self>, deadline: Instant)
将该 Sleep 实例重置为一个新的截止时间。
调用此函数允许在不创建新的关联状态的情况下,更改 Sleep future 完成的 instant。
此函数可在 future 完成之前或之后调用。
要调用此方法,通常需要将调用与 Pin::as_mut 结合使用,从而在不必消耗 Sleep 自身的前提下调用该方法。
§Example
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 实现§
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Mutably borrows from an owned value. 更多信息
Source§impl<F> IntoFuture for Fwhere
F: Future,
impl<F> IntoFuture for Fwhere
F: Future,
Source§type IntoFuture = F
type IntoFuture = F
我们将要把此值转变成哪种 future?
Source§fn into_future(self) -> <F as IntoFuture>::IntoFuture
fn into_future(self) -> <F as IntoFuture>::IntoFuture
Creates a future from a value. 更多信息