time: introduce sleep and sleep_until functions (#2826)

This commit is contained in:
Juan Alvarez
2020-10-01 09:24:33 +02:00
committed by GitHub
parent 971ed2c6df
commit 53ccfc1fd6
31 changed files with 152 additions and 153 deletions
+2 -2
View File
@@ -365,7 +365,7 @@ impl AsyncRead for Mock {
Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => { Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => {
if let Some(rem) = self.inner.remaining_wait() { if let Some(rem) = self.inner.remaining_wait() {
let until = Instant::now() + rem; let until = Instant::now() + rem;
self.inner.sleep = Some(time::delay_until(until)); self.inner.sleep = Some(time::sleep_until(until));
} else { } else {
self.inner.read_wait = Some(cx.waker().clone()); self.inner.read_wait = Some(cx.waker().clone());
return Poll::Pending; return Poll::Pending;
@@ -410,7 +410,7 @@ impl AsyncWrite for Mock {
Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => { Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => {
if let Some(rem) = self.inner.remaining_wait() { if let Some(rem) = self.inner.remaining_wait() {
let until = Instant::now() + rem; let until = Instant::now() + rem;
self.inner.sleep = Some(time::delay_until(until)); self.inner.sleep = Some(time::sleep_until(until));
} else { } else {
panic!("unexpected WouldBlock"); panic!("unexpected WouldBlock");
} }
+2 -2
View File
@@ -1,6 +1,6 @@
#![warn(rust_2018_idioms)] #![warn(rust_2018_idioms)]
use tokio::time::{delay_until, Duration, Instant}; use tokio::time::{sleep_until, Duration, Instant};
use tokio_test::block_on; use tokio_test::block_on;
#[test] #[test]
@@ -22,6 +22,6 @@ fn test_delay() {
let deadline = Instant::now() + Duration::from_millis(100); let deadline = Instant::now() + Duration::from_millis(100);
block_on(async { block_on(async {
delay_until(deadline).await; sleep_until(deadline).await;
}); });
} }
+3 -3
View File
@@ -46,7 +46,7 @@ pub trait RuntimeExt {
/// ///
/// ```no_run /// ```no_run
/// use tokio_util::context::RuntimeExt; /// use tokio_util::context::RuntimeExt;
/// use tokio::time::{delay_for, Duration}; /// use tokio::time::{sleep, Duration};
/// ///
/// let rt = tokio::runtime::Builder::new() /// let rt = tokio::runtime::Builder::new()
/// .threaded_scheduler() /// .threaded_scheduler()
@@ -57,11 +57,11 @@ pub trait RuntimeExt {
/// .threaded_scheduler() /// .threaded_scheduler()
/// .build().unwrap(); /// .build().unwrap();
/// ///
/// let fut = delay_for(Duration::from_millis(2)); /// let fut = sleep(Duration::from_millis(2));
/// ///
/// rt.block_on( /// rt.block_on(
/// rt2 /// rt2
/// .wrap(async { delay_for(Duration::from_millis(2)).await }), /// .wrap(async { sleep(Duration::from_millis(2)).await }),
/// ); /// );
///``` ///```
fn wrap<F: Future>(&self, fut: F) -> TokioContext<'_, F>; fn wrap<F: Future>(&self, fut: F) -> TokioContext<'_, F>;
+4 -4
View File
@@ -37,14 +37,14 @@ use core::task::{Context, Poll, Waker};
/// // The token was cancelled /// // The token was cancelled
/// 5 /// 5
/// } /// }
/// _ = tokio::time::delay_for(std::time::Duration::from_secs(9999)) => { /// _ = tokio::time::sleep(std::time::Duration::from_secs(9999)) => {
/// 99 /// 99
/// } /// }
/// } /// }
/// }); /// });
/// ///
/// tokio::spawn(async move { /// tokio::spawn(async move {
/// tokio::time::delay_for(std::time::Duration::from_millis(10)).await; /// tokio::time::sleep(std::time::Duration::from_millis(10)).await;
/// token.cancel(); /// token.cancel();
/// }); /// });
/// ///
@@ -185,14 +185,14 @@ impl CancellationToken {
/// // The token was cancelled /// // The token was cancelled
/// 5 /// 5
/// } /// }
/// _ = tokio::time::delay_for(std::time::Duration::from_secs(9999)) => { /// _ = tokio::time::sleep(std::time::Duration::from_secs(9999)) => {
/// 99 /// 99
/// } /// }
/// } /// }
/// }); /// });
/// ///
/// tokio::spawn(async move { /// tokio::spawn(async move {
/// tokio::time::delay_for(std::time::Duration::from_millis(10)).await; /// tokio::time::sleep(std::time::Duration::from_millis(10)).await;
/// token.cancel(); /// token.cancel();
/// }); /// });
/// ///
+1 -1
View File
@@ -21,5 +21,5 @@ fn tokio_context_with_another_runtime() {
// Without the `HandleExt.wrap()` there would be a panic because there is // Without the `HandleExt.wrap()` there would be a panic because there is
// no timer running, since it would be referencing runtime r1. // no timer running, since it would be referencing runtime r1.
let _ = rt1.block_on(rt2.wrap(async move { delay_for(Duration::from_millis(2)).await })); let _ = rt1.block_on(rt2.wrap(async move { sleep(Duration::from_millis(2)).await }));
} }
+1 -1
View File
@@ -189,7 +189,7 @@
//! In order to use `tokio::time`, the "time" feature flag must be enabled. //! In order to use `tokio::time`, the "time" feature flag must be enabled.
//! //!
//! [`tokio::time`]: crate::time //! [`tokio::time`]: crate::time
//! [delay]: crate::time::delay_for() //! [delay]: crate::time::sleep()
//! [interval]: crate::time::interval() //! [interval]: crate::time::interval()
//! [timeout]: crate::time::timeout() //! [timeout]: crate::time::timeout()
//! //!
+4 -4
View File
@@ -76,7 +76,7 @@
/// ///
/// #[tokio::main] /// #[tokio::main]
/// async fn main() { /// async fn main() {
/// let mut delay = time::delay_for(Duration::from_millis(50)); /// let mut delay = time::sleep(Duration::from_millis(50));
/// ///
/// while !delay.is_elapsed() { /// while !delay.is_elapsed() {
/// tokio::select! { /// tokio::select! {
@@ -103,13 +103,13 @@
/// use tokio::time::{self, Duration}; /// use tokio::time::{self, Duration};
/// ///
/// async fn some_async_work() { /// async fn some_async_work() {
/// # time::delay_for(Duration::from_millis(10)).await; /// # time::sleep(Duration::from_millis(10)).await;
/// // do work /// // do work
/// } /// }
/// ///
/// #[tokio::main] /// #[tokio::main]
/// async fn main() { /// async fn main() {
/// let mut delay = time::delay_for(Duration::from_millis(50)); /// let mut delay = time::sleep(Duration::from_millis(50));
/// ///
/// loop { /// loop {
/// tokio::select! { /// tokio::select! {
@@ -226,7 +226,7 @@
/// #[tokio::main] /// #[tokio::main]
/// async fn main() { /// async fn main() {
/// let mut stream = stream::iter(vec![1, 2, 3]); /// let mut stream = stream::iter(vec![1, 2, 3]);
/// let mut delay = time::delay_for(Duration::from_secs(1)); /// let mut delay = time::sleep(Duration::from_secs(1));
/// ///
/// loop { /// loop {
/// tokio::select! { /// tokio::select! {
+4 -4
View File
@@ -121,7 +121,7 @@ doc_rt_core! {
/// let original_task = task::spawn(async { /// let original_task = task::spawn(async {
/// let _detached_task = task::spawn(async { /// let _detached_task = task::spawn(async {
/// // Here we sleep to make sure that the first task returns before. /// // Here we sleep to make sure that the first task returns before.
/// time::delay_for(Duration::from_millis(10)).await; /// time::sleep(Duration::from_millis(10)).await;
/// // This will be called, even though the JoinHandle is dropped. /// // This will be called, even though the JoinHandle is dropped.
/// println!("♫ Still alive ♫"); /// println!("♫ Still alive ♫");
/// }); /// });
@@ -133,7 +133,7 @@ doc_rt_core! {
/// // We make sure that the new task has time to run, before the main /// // We make sure that the new task has time to run, before the main
/// // task returns. /// // task returns.
/// ///
/// time::delay_for(Duration::from_millis(1000)).await; /// time::sleep(Duration::from_millis(1000)).await;
/// # } /// # }
/// ``` /// ```
/// ///
@@ -172,12 +172,12 @@ impl<T> JoinHandle<T> {
/// let mut handles = Vec::new(); /// let mut handles = Vec::new();
/// ///
/// handles.push(tokio::spawn(async { /// handles.push(tokio::spawn(async {
/// time::delay_for(time::Duration::from_secs(10)).await; /// time::sleep(time::Duration::from_secs(10)).await;
/// true /// true
/// })); /// }));
/// ///
/// handles.push(tokio::spawn(async { /// handles.push(tokio::spawn(async {
/// time::delay_for(time::Duration::from_secs(10)).await; /// time::sleep(time::Duration::from_secs(10)).await;
/// false /// false
/// })); /// }));
/// ///
+3 -3
View File
@@ -281,18 +281,18 @@ pub trait StreamExt: Stream {
/// tx1.send(2).await.unwrap(); /// tx1.send(2).await.unwrap();
/// ///
/// // Let the other task send values /// // Let the other task send values
/// time::delay_for(Duration::from_millis(20)).await; /// time::sleep(Duration::from_millis(20)).await;
/// ///
/// tx1.send(4).await.unwrap(); /// tx1.send(4).await.unwrap();
/// }); /// });
/// ///
/// tokio::spawn(async move { /// tokio::spawn(async move {
/// // Wait for the first task to send values /// // Wait for the first task to send values
/// time::delay_for(Duration::from_millis(5)).await; /// time::sleep(Duration::from_millis(5)).await;
/// ///
/// tx2.send(3).await.unwrap(); /// tx2.send(3).await.unwrap();
/// ///
/// time::delay_for(Duration::from_millis(25)).await; /// time::sleep(Duration::from_millis(25)).await;
/// ///
/// // Send the final value /// // Send the final value
/// tx2.send(5).await.unwrap(); /// tx2.send(5).await.unwrap();
+3 -3
View File
@@ -322,7 +322,7 @@
//! tokio::spawn(async move { //! tokio::spawn(async move {
//! loop { //! loop {
//! // Wait 10 seconds between checks //! // Wait 10 seconds between checks
//! time::delay_for(Duration::from_secs(10)).await; //! time::sleep(Duration::from_secs(10)).await;
//! //!
//! // Load the configuration file //! // Load the configuration file
//! let new_config = Config::load_from_file().await.unwrap(); //! let new_config = Config::load_from_file().await.unwrap();
@@ -359,7 +359,7 @@
//! let mut conf = rx.borrow().clone(); //! let mut conf = rx.borrow().clone();
//! //!
//! let mut op_start = Instant::now(); //! let mut op_start = Instant::now();
//! let mut delay = time::delay_until(op_start + conf.timeout); //! let mut delay = time::sleep_until(op_start + conf.timeout);
//! //!
//! loop { //! loop {
//! tokio::select! { //! tokio::select! {
@@ -371,7 +371,7 @@
//! op_start = Instant::now(); //! op_start = Instant::now();
//! //!
//! // Restart the timeout //! // Restart the timeout
//! delay = time::delay_until(op_start + conf.timeout); //! delay = time::sleep_until(op_start + conf.timeout);
//! } //! }
//! _ = rx.changed() => { //! _ = rx.changed() => {
//! conf = rx.borrow().clone(); //! conf = rx.borrow().clone();
+2 -2
View File
@@ -449,7 +449,7 @@ impl<T> Sender<T> {
/// ///
/// ```rust /// ```rust
/// use tokio::sync::mpsc; /// use tokio::sync::mpsc;
/// use tokio::time::{delay_for, Duration}; /// use tokio::time::{sleep, Duration};
/// ///
/// #[tokio::main] /// #[tokio::main]
/// async fn main() { /// async fn main() {
@@ -466,7 +466,7 @@ impl<T> Sender<T> {
/// ///
/// while let Some(i) = rx.recv().await { /// while let Some(i) = rx.recv().await {
/// println!("got = {}", i); /// println!("got = {}", i);
/// delay_for(Duration::from_millis(200)).await; /// sleep(Duration::from_millis(200)).await;
/// } /// }
/// } /// }
/// ``` /// ```
+1 -1
View File
@@ -95,7 +95,7 @@ cfg_rt_util! {
/// }); /// });
/// ///
/// local.spawn_local(async move { /// local.spawn_local(async move {
/// time::delay_for(time::Duration::from_millis(100)).await; /// time::sleep(time::Duration::from_millis(100)).await;
/// println!("goodbye {}", unsend_data) /// println!("goodbye {}", unsend_data)
/// }); /// });
/// ///
+9 -10
View File
@@ -15,14 +15,14 @@ use std::task::{self, Poll};
/// ///
/// Canceling a delay is done by dropping the returned future. No additional /// Canceling a delay is done by dropping the returned future. No additional
/// cleanup work is required. /// cleanup work is required.
pub fn delay_until(deadline: Instant) -> Delay { pub fn sleep_until(deadline: Instant) -> Delay {
let registration = Registration::new(deadline, Duration::from_millis(0)); let registration = Registration::new(deadline, Duration::from_millis(0));
Delay { registration } Delay { registration }
} }
/// Waits until `duration` has elapsed. /// Waits until `duration` has elapsed.
/// ///
/// Equivalent to `delay_until(Instant::now() + duration)`. An asynchronous /// Equivalent to `sleep_until(Instant::now() + duration)`. An asynchronous
/// analog to `std::thread::sleep`. /// analog to `std::thread::sleep`.
/// ///
/// No work is performed while awaiting on the delay to complete. The delay /// No work is performed while awaiting on the delay to complete. The delay
@@ -41,23 +41,22 @@ pub fn delay_until(deadline: Instant) -> Delay {
/// Wait 100ms and print "100 ms have elapsed". /// Wait 100ms and print "100 ms have elapsed".
/// ///
/// ``` /// ```
/// use tokio::time::{delay_for, Duration}; /// use tokio::time::{sleep, Duration};
/// ///
/// #[tokio::main] /// #[tokio::main]
/// async fn main() { /// async fn main() {
/// delay_for(Duration::from_millis(100)).await; /// sleep(Duration::from_millis(100)).await;
/// println!("100 ms have elapsed"); /// println!("100 ms have elapsed");
/// } /// }
/// ``` /// ```
/// ///
/// [`interval`]: crate::time::interval() /// [`interval`]: crate::time::interval()
#[cfg_attr(docsrs, doc(alias = "sleep"))] pub fn sleep(duration: Duration) -> Delay {
pub fn delay_for(duration: Duration) -> Delay { sleep_until(Instant::now() + duration)
delay_until(Instant::now() + duration)
} }
/// Future returned by [`delay_until`](delay_until) and /// Future returned by [`sleep`](sleep) and
/// [`delay_for`](delay_for). /// [`sleep_until`](sleep_until).
#[derive(Debug)] #[derive(Debug)]
#[must_use = "futures do nothing unless you `.await` or poll them"] #[must_use = "futures do nothing unless you `.await` or poll them"]
pub struct Delay { pub struct Delay {
@@ -103,7 +102,7 @@ impl Future for Delay {
fn poll(self: Pin<&mut Self>, cx: &mut task::Context<'_>) -> Poll<Self::Output> { fn poll(self: Pin<&mut Self>, cx: &mut task::Context<'_>) -> Poll<Self::Output> {
// `poll_elapsed` can return an error in two cases: // `poll_elapsed` can return an error in two cases:
// //
// - AtCapacity: this is a pathlogical case where far too many // - AtCapacity: this is a pathological case where far too many
// delays have been scheduled. // delays have been scheduled.
// - Shutdown: No timer has been setup, which is a mis-use error. // - Shutdown: No timer has been setup, which is a mis-use error.
// //
+5 -5
View File
@@ -5,7 +5,7 @@
//! [`DelayQueue`]: struct@DelayQueue //! [`DelayQueue`]: struct@DelayQueue
use crate::time::wheel::{self, Wheel}; use crate::time::wheel::{self, Wheel};
use crate::time::{delay_until, Delay, Duration, Error, Instant}; use crate::time::{sleep_until, Delay, Duration, Error, Instant};
use slab::Slab; use slab::Slab;
use std::cmp; use std::cmp;
@@ -51,7 +51,7 @@ use std::task::{self, Poll};
/// # Implementation /// # Implementation
/// ///
/// The [`DelayQueue`] is backed by a separate instance of the same timer wheel used internally by /// The [`DelayQueue`] is backed by a separate instance of the same timer wheel used internally by
/// Tokio's standalone timer utilities such as [`delay_for`]. Because of this, it offers the same /// Tokio's standalone timer utilities such as [`sleep`]. Because of this, it offers the same
/// performance and scalability benefits. /// performance and scalability benefits.
/// ///
/// State associated with each entry is stored in a [`slab`]. This amortizes the cost of allocation, /// State associated with each entry is stored in a [`slab`]. This amortizes the cost of allocation,
@@ -118,7 +118,7 @@ use std::task::{self, Poll};
/// [`poll_expired`]: method@Self::poll_expired /// [`poll_expired`]: method@Self::poll_expired
/// [`Stream::poll_expired`]: method@Self::poll_expired /// [`Stream::poll_expired`]: method@Self::poll_expired
/// [`DelayQueue`]: struct@DelayQueue /// [`DelayQueue`]: struct@DelayQueue
/// [`delay_for`]: fn@super::delay_for /// [`sleep`]: fn@super::sleep
/// [`slab`]: slab /// [`slab`]: slab
/// [`capacity`]: method@Self::capacity /// [`capacity`]: method@Self::capacity
/// [`reserve`]: method@Self::reserve /// [`reserve`]: method@Self::reserve
@@ -330,7 +330,7 @@ impl<T> DelayQueue<T> {
if let Some(ref mut delay) = &mut self.delay { if let Some(ref mut delay) = &mut self.delay {
delay.reset(delay_time); delay.reset(delay_time);
} else { } else {
self.delay = Some(delay_until(delay_time)); self.delay = Some(sleep_until(delay_time));
} }
} }
@@ -734,7 +734,7 @@ impl<T> DelayQueue<T> {
// We poll the wheel to get the next value out before finding the next deadline. // We poll the wheel to get the next value out before finding the next deadline.
let wheel_idx = self.wheel.poll(&mut self.poll, &mut self.slab); let wheel_idx = self.wheel.poll(&mut self.poll, &mut self.slab);
self.delay = self.next_deadline().map(delay_until); self.delay = self.next_deadline().map(sleep_until);
if let Some(idx) = wheel_idx { if let Some(idx) = wheel_idx {
return Poll::Ready(Some(Ok(idx))); return Poll::Ready(Some(Ok(idx)));
+2 -2
View File
@@ -25,9 +25,9 @@ impl Handle {
/// `Builder::enable_all()` are not included in the builder. /// `Builder::enable_all()` are not included in the builder.
/// ///
/// It can also panic whenever a timer is created outside of a Tokio /// It can also panic whenever a timer is created outside of a Tokio
/// runtime. That is why `rt.block_on(delay_for(...))` will panic, /// runtime. That is why `rt.block_on(sleep(...))` will panic,
/// since the function is executed outside of the runtime. /// since the function is executed outside of the runtime.
/// Whereas `rt.block_on(async {delay_for(...).await})` doesn't /// Whereas `rt.block_on(async {sleep(...).await})` doesn't
/// panic. And this is because wrapping the function on an async makes it /// panic. And this is because wrapping the function on an async makes it
/// lazy, and so gets executed inside the runtime successfuly without /// lazy, and so gets executed inside the runtime successfuly without
/// panicking. /// panicking.
+6 -6
View File
@@ -50,12 +50,12 @@ impl Instant {
/// # Examples /// # Examples
/// ///
/// ``` /// ```
/// use tokio::time::{Duration, Instant, delay_for}; /// use tokio::time::{Duration, Instant, sleep};
/// ///
/// #[tokio::main] /// #[tokio::main]
/// async fn main() { /// async fn main() {
/// let now = Instant::now(); /// let now = Instant::now();
/// delay_for(Duration::new(1, 0)).await; /// sleep(Duration::new(1, 0)).await;
/// let new_now = Instant::now(); /// let new_now = Instant::now();
/// println!("{:?}", new_now.checked_duration_since(now)); /// println!("{:?}", new_now.checked_duration_since(now));
/// println!("{:?}", now.checked_duration_since(new_now)); // None /// println!("{:?}", now.checked_duration_since(new_now)); // None
@@ -71,12 +71,12 @@ impl Instant {
/// # Examples /// # Examples
/// ///
/// ``` /// ```
/// use tokio::time::{Duration, Instant, delay_for}; /// use tokio::time::{Duration, Instant, sleep};
/// ///
/// #[tokio::main] /// #[tokio::main]
/// async fn main() { /// async fn main() {
/// let now = Instant::now(); /// let now = Instant::now();
/// delay_for(Duration::new(1, 0)).await; /// sleep(Duration::new(1, 0)).await;
/// let new_now = Instant::now(); /// let new_now = Instant::now();
/// println!("{:?}", new_now.saturating_duration_since(now)); /// println!("{:?}", new_now.saturating_duration_since(now));
/// println!("{:?}", now.saturating_duration_since(new_now)); // 0ns /// println!("{:?}", now.saturating_duration_since(new_now)); // 0ns
@@ -97,13 +97,13 @@ impl Instant {
/// # Examples /// # Examples
/// ///
/// ``` /// ```
/// use tokio::time::{Duration, Instant, delay_for}; /// use tokio::time::{Duration, Instant, sleep};
/// ///
/// #[tokio::main] /// #[tokio::main]
/// async fn main() { /// async fn main() {
/// let instant = Instant::now(); /// let instant = Instant::now();
/// let three_secs = Duration::from_secs(3); /// let three_secs = Duration::from_secs(3);
/// delay_for(three_secs).await; /// sleep(three_secs).await;
/// assert!(instant.elapsed() >= three_secs); /// assert!(instant.elapsed() >= three_secs);
/// } /// }
/// ``` /// ```
+6 -6
View File
@@ -1,5 +1,5 @@
use crate::future::poll_fn; use crate::future::poll_fn;
use crate::time::{delay_until, Delay, Duration, Instant}; use crate::time::{sleep_until, Delay, Duration, Instant};
use std::future::Future; use std::future::Future;
use std::pin::Pin; use std::pin::Pin;
@@ -36,12 +36,12 @@ use std::task::{Context, Poll};
/// ///
/// A simple example using `interval` to execute a task every two seconds. /// A simple example using `interval` to execute a task every two seconds.
/// ///
/// The difference between `interval` and [`delay_for`] is that an `interval` /// The difference between `interval` and [`sleep`] is that an `interval`
/// measures the time since the last tick, which means that `.tick().await` /// measures the time since the last tick, which means that `.tick().await`
/// may wait for a shorter time than the duration specified for the interval /// may wait for a shorter time than the duration specified for the interval
/// if some time has passed between calls to `.tick().await`. /// if some time has passed between calls to `.tick().await`.
/// ///
/// If the tick in the example below was replaced with [`delay_for`], the task /// If the tick in the example below was replaced with [`sleep`], the task
/// would only be executed once every three seconds, and not every two /// would only be executed once every three seconds, and not every two
/// seconds. /// seconds.
/// ///
@@ -50,7 +50,7 @@ use std::task::{Context, Poll};
/// ///
/// async fn task_that_takes_a_second() { /// async fn task_that_takes_a_second() {
/// println!("hello"); /// println!("hello");
/// time::delay_for(time::Duration::from_secs(1)).await /// time::sleep(time::Duration::from_secs(1)).await
/// } /// }
/// ///
/// #[tokio::main] /// #[tokio::main]
@@ -63,7 +63,7 @@ use std::task::{Context, Poll};
/// } /// }
/// ``` /// ```
/// ///
/// [`delay_for`]: crate::time::delay_for() /// [`sleep`]: crate::time::sleep()
pub fn interval(period: Duration) -> Interval { pub fn interval(period: Duration) -> Interval {
assert!(period > Duration::new(0, 0), "`period` must be non-zero."); assert!(period > Duration::new(0, 0), "`period` must be non-zero.");
@@ -101,7 +101,7 @@ pub fn interval_at(start: Instant, period: Duration) -> Interval {
assert!(period > Duration::new(0, 0), "`period` must be non-zero."); assert!(period > Duration::new(0, 0), "`period` must be non-zero.");
Interval { Interval {
delay: delay_until(start), delay: sleep_until(start),
period, period,
} }
} }
+7 -7
View File
@@ -27,14 +27,14 @@
//! Wait 100ms and print "100 ms have elapsed" //! Wait 100ms and print "100 ms have elapsed"
//! //!
//! ``` //! ```
//! use tokio::time::delay_for; //! use tokio::time::sleep;
//! //!
//! use std::time::Duration; //! use std::time::Duration;
//! //!
//! //!
//! #[tokio::main] //! #[tokio::main]
//! async fn main() { //! async fn main() {
//! delay_for(Duration::from_millis(100)).await; //! sleep(Duration::from_millis(100)).await;
//! println!("100 ms have elapsed"); //! println!("100 ms have elapsed");
//! } //! }
//! ``` //! ```
@@ -61,12 +61,12 @@
//! //!
//! A simple example using [`interval`] to execute a task every two seconds. //! A simple example using [`interval`] to execute a task every two seconds.
//! //!
//! The difference between [`interval`] and [`delay_for`] is that an //! The difference between [`interval`] and [`sleep`] is that an
//! [`interval`] measures the time since the last tick, which means that //! [`interval`] measures the time since the last tick, which means that
//! `.tick().await` may wait for a shorter time than the duration specified //! `.tick().await` may wait for a shorter time than the duration specified
//! for the interval if some time has passed between calls to `.tick().await`. //! for the interval if some time has passed between calls to `.tick().await`.
//! //!
//! If the tick in the example below was replaced with [`delay_for`], the task //! If the tick in the example below was replaced with [`sleep`], the task
//! would only be executed once every three seconds, and not every two //! would only be executed once every three seconds, and not every two
//! seconds. //! seconds.
//! //!
@@ -75,7 +75,7 @@
//! //!
//! async fn task_that_takes_a_second() { //! async fn task_that_takes_a_second() {
//! println!("hello"); //! println!("hello");
//! time::delay_for(time::Duration::from_secs(1)).await //! time::sleep(time::Duration::from_secs(1)).await
//! } //! }
//! //!
//! #[tokio::main] //! #[tokio::main]
@@ -88,7 +88,7 @@
//! } //! }
//! ``` //! ```
//! //!
//! [`delay_for`]: crate::time::delay_for() //! [`sleep`]: crate::time::sleep()
//! [`interval`]: crate::time::interval() //! [`interval`]: crate::time::interval()
mod clock; mod clock;
@@ -101,7 +101,7 @@ pub mod delay_queue;
pub use delay_queue::DelayQueue; pub use delay_queue::DelayQueue;
mod delay; mod delay;
pub use delay::{delay_for, delay_until, Delay}; pub use delay::{sleep, sleep_until, Delay};
pub(crate) mod driver; pub(crate) mod driver;
+1 -1
View File
@@ -18,5 +18,5 @@ fn registration_is_send_and_sync() {
#[should_panic] #[should_panic]
fn delay_is_eager() { fn delay_is_eager() {
let when = Instant::now() + Duration::from_millis(100); let when = Instant::now() + Duration::from_millis(100);
let _ = time::delay_until(when); let _ = time::sleep_until(when);
} }
+2 -2
View File
@@ -4,7 +4,7 @@
//! //!
//! [`Timeout`]: struct@Timeout //! [`Timeout`]: struct@Timeout
use crate::time::{delay_until, Delay, Duration, Instant}; use crate::time::{sleep_until, Delay, Duration, Instant};
use pin_project_lite::pin_project; use pin_project_lite::pin_project;
use std::fmt; use std::fmt;
@@ -92,7 +92,7 @@ pub fn timeout_at<T>(deadline: Instant, future: T) -> Timeout<T>
where where
T: Future, T: Future,
{ {
let delay = delay_until(deadline); let delay = sleep_until(deadline);
Timeout { Timeout {
value: future, value: future,
+2 -2
View File
@@ -243,8 +243,8 @@ async_assert_fn!(tokio::task::LocalSet::run_until(_, BoxFutureSync<()>): !Send &
assert_value!(tokio::task::LocalSet: !Send & !Sync); assert_value!(tokio::task::LocalSet: !Send & !Sync);
async_assert_fn!(tokio::time::advance(Duration): Send & Sync); async_assert_fn!(tokio::time::advance(Duration): Send & Sync);
async_assert_fn!(tokio::time::delay_for(Duration): Send & Sync); async_assert_fn!(tokio::time::sleep(Duration): Send & Sync);
async_assert_fn!(tokio::time::delay_until(Instant): Send & Sync); async_assert_fn!(tokio::time::sleep_until(Instant): Send & Sync);
async_assert_fn!(tokio::time::timeout(Duration, BoxFutureSync<()>): Send & Sync); async_assert_fn!(tokio::time::timeout(Duration, BoxFutureSync<()>): Send & Sync);
async_assert_fn!(tokio::time::timeout(Duration, BoxFutureSend<()>): Send & !Sync); async_assert_fn!(tokio::time::timeout(Duration, BoxFutureSend<()>): Send & !Sync);
async_assert_fn!(tokio::time::timeout(Duration, BoxFuture<()>): !Send & !Sync); async_assert_fn!(tokio::time::timeout(Duration, BoxFuture<()>): !Send & !Sync);
+2 -2
View File
@@ -359,7 +359,7 @@ async fn join_with_select() {
async fn use_future_in_if_condition() { async fn use_future_in_if_condition() {
use tokio::time::{self, Duration}; use tokio::time::{self, Duration};
let mut delay = time::delay_for(Duration::from_millis(50)); let mut delay = time::sleep(Duration::from_millis(50));
tokio::select! { tokio::select! {
_ = &mut delay, if !delay.is_elapsed() => { _ = &mut delay, if !delay.is_elapsed() => {
@@ -459,7 +459,7 @@ async fn async_noop() {}
async fn async_never() -> ! { async fn async_never() -> ! {
use tokio::time::Duration; use tokio::time::Duration;
loop { loop {
tokio::time::delay_for(Duration::from_millis(10)).await; tokio::time::sleep(Duration::from_millis(10)).await;
} }
} }
+1 -1
View File
@@ -36,7 +36,7 @@ async fn issue_2174() {
}); });
// Sleep enough time so that the child process's stdin's buffer fills. // Sleep enough time so that the child process's stdin's buffer fills.
time::delay_for(Duration::from_secs(1)).await; time::sleep(Duration::from_secs(1)).await;
// Kill the child process. // Kill the child process.
child.kill().await.unwrap(); child.kill().await.unwrap();
+2 -2
View File
@@ -5,7 +5,7 @@ use std::process::Stdio;
use std::time::Duration; use std::time::Duration;
use tokio::io::AsyncReadExt; use tokio::io::AsyncReadExt;
use tokio::process::Command; use tokio::process::Command;
use tokio::time::delay_for; use tokio::time::sleep;
use tokio_test::assert_ok; use tokio_test::assert_ok;
#[tokio::test] #[tokio::test]
@@ -30,7 +30,7 @@ async fn kill_on_drop() {
.spawn() .spawn()
.unwrap(); .unwrap();
delay_for(Duration::from_secs(2)).await; sleep(Duration::from_secs(2)).await;
let mut out = child.stdout.take().unwrap(); let mut out = child.stdout.take().unwrap();
drop(child); drop(child);
+10 -10
View File
@@ -437,7 +437,7 @@ rt_test! {
let dur = Duration::from_millis(50); let dur = Duration::from_millis(50);
rt.block_on(async move { rt.block_on(async move {
time::delay_for(dur).await; time::sleep(dur).await;
}); });
assert!(now.elapsed() >= dur); assert!(now.elapsed() >= dur);
@@ -454,7 +454,7 @@ rt_test! {
let (tx, rx) = oneshot::channel(); let (tx, rx) = oneshot::channel();
tokio::spawn(async move { tokio::spawn(async move {
time::delay_for(dur).await; time::sleep(dur).await;
assert_ok!(tx.send(())); assert_ok!(tx.send(()));
}); });
@@ -526,7 +526,7 @@ rt_test! {
// use the futures' block_on fn to make sure we aren't setting // use the futures' block_on fn to make sure we aren't setting
// any Tokio context // any Tokio context
futures::executor::block_on(async { futures::executor::block_on(async {
tokio::time::delay_for(dur).await; tokio::time::sleep(dur).await;
}); });
assert!(now.elapsed() >= dur); assert!(now.elapsed() >= dur);
@@ -588,7 +588,7 @@ rt_test! {
let jh1 = thread::spawn(move || { let jh1 = thread::spawn(move || {
rt.block_on(async move { rt.block_on(async move {
rx2.await.unwrap(); rx2.await.unwrap();
time::delay_for(Duration::from_millis(5)).await; time::sleep(Duration::from_millis(5)).await;
tx1.send(()).unwrap(); tx1.send(()).unwrap();
}); });
}); });
@@ -596,9 +596,9 @@ rt_test! {
let jh2 = thread::spawn(move || { let jh2 = thread::spawn(move || {
rt2.block_on(async move { rt2.block_on(async move {
tx2.send(()).unwrap(); tx2.send(()).unwrap();
time::delay_for(Duration::from_millis(5)).await; time::sleep(Duration::from_millis(5)).await;
rx1.await.unwrap(); rx1.await.unwrap();
time::delay_for(Duration::from_millis(5)).await; time::sleep(Duration::from_millis(5)).await;
}); });
}); });
@@ -850,11 +850,11 @@ rt_test! {
let buf = [0]; let buf = [0];
loop { loop {
send_half.send_to(&buf, &addr).await.unwrap(); send_half.send_to(&buf, &addr).await.unwrap();
tokio::time::delay_for(Duration::from_millis(1)).await; tokio::time::sleep(Duration::from_millis(1)).await;
} }
}); });
tokio::time::delay_for(Duration::from_millis(5)).await; tokio::time::sleep(Duration::from_millis(5)).await;
}); });
} }
} }
@@ -881,7 +881,7 @@ rt_test! {
let runtime = rt(); let runtime = rt();
runtime.block_on(async move { runtime.block_on(async move {
tokio::time::delay_for(std::time::Duration::from_millis(100)).await; tokio::time::sleep(std::time::Duration::from_millis(100)).await;
}); });
Arc::try_unwrap(runtime).unwrap().shutdown_timeout(Duration::from_secs(10_000)); Arc::try_unwrap(runtime).unwrap().shutdown_timeout(Duration::from_secs(10_000));
@@ -1006,7 +1006,7 @@ rt_test! {
}).collect::<Vec<_>>(); }).collect::<Vec<_>>();
// Hope that all the tasks complete... // Hope that all the tasks complete...
time::delay_for(Duration::from_millis(100)).await; time::sleep(Duration::from_millis(100)).await;
poll_fn(|cx| { poll_fn(|cx| {
// At least one task should not be ready // At least one task should not be ready
+2 -2
View File
@@ -1,14 +1,14 @@
#![cfg(feature = "full")] #![cfg(feature = "full")]
use tokio::stream::{self, StreamExt}; use tokio::stream::{self, StreamExt};
use tokio::time::{self, delay_for, Duration}; use tokio::time::{self, sleep, Duration};
use tokio_test::*; use tokio_test::*;
use futures::StreamExt as _; use futures::StreamExt as _;
async fn maybe_delay(idx: i32) -> i32 { async fn maybe_delay(idx: i32) -> i32 {
if idx % 2 == 0 { if idx % 2 == 0 {
delay_for(ms(200)).await; sleep(ms(200)).await;
} }
idx idx
} }
+1 -1
View File
@@ -16,7 +16,7 @@ async fn local() {
assert_eq!(*v, 2); assert_eq!(*v, 2);
}); });
tokio::time::delay_for(std::time::Duration::from_millis(10)).await; tokio::time::sleep(std::time::Duration::from_millis(10)).await;
assert_eq!(REQ_ID.get(), 2); assert_eq!(REQ_ID.get(), 2);
})); }));
+8 -8
View File
@@ -62,11 +62,11 @@ async fn localset_future_timers() {
let local = LocalSet::new(); let local = LocalSet::new();
local.spawn_local(async move { local.spawn_local(async move {
time::delay_for(Duration::from_millis(10)).await; time::sleep(Duration::from_millis(10)).await;
RAN1.store(true, Ordering::SeqCst); RAN1.store(true, Ordering::SeqCst);
}); });
local.spawn_local(async move { local.spawn_local(async move {
time::delay_for(Duration::from_millis(20)).await; time::sleep(Duration::from_millis(20)).await;
RAN2.store(true, Ordering::SeqCst); RAN2.store(true, Ordering::SeqCst);
}); });
local.await; local.await;
@@ -114,7 +114,7 @@ async fn local_threadpool_timer() {
assert!(ON_RT_THREAD.with(|cell| cell.get())); assert!(ON_RT_THREAD.with(|cell| cell.get()));
let join = task::spawn_local(async move { let join = task::spawn_local(async move {
assert!(ON_RT_THREAD.with(|cell| cell.get())); assert!(ON_RT_THREAD.with(|cell| cell.get()));
time::delay_for(Duration::from_millis(10)).await; time::sleep(Duration::from_millis(10)).await;
assert!(ON_RT_THREAD.with(|cell| cell.get())); assert!(ON_RT_THREAD.with(|cell| cell.get()));
}); });
join.await.unwrap(); join.await.unwrap();
@@ -299,7 +299,7 @@ fn drop_cancels_tasks() {
started_tx.send(()).unwrap(); started_tx.send(()).unwrap();
loop { loop {
time::delay_for(Duration::from_secs(3600)).await; time::sleep(Duration::from_secs(3600)).await;
} }
}); });
@@ -367,7 +367,7 @@ fn drop_cancels_remote_tasks() {
let local = LocalSet::new(); let local = LocalSet::new();
local.spawn_local(async move { while rx.recv().await.is_some() {} }); local.spawn_local(async move { while rx.recv().await.is_some() {} });
local.block_on(&rt, async { local.block_on(&rt, async {
time::delay_for(Duration::from_millis(1)).await; time::sleep(Duration::from_millis(1)).await;
}); });
drop(tx); drop(tx);
@@ -415,7 +415,7 @@ async fn local_tasks_are_polled_after_tick() {
.run_until(async { .run_until(async {
let task2 = task::spawn(async move { let task2 = task::spawn(async move {
// Wait a bit // Wait a bit
time::delay_for(Duration::from_millis(100)).await; time::sleep(Duration::from_millis(100)).await;
let mut oneshots = Vec::with_capacity(EXPECTED); let mut oneshots = Vec::with_capacity(EXPECTED);
@@ -426,13 +426,13 @@ async fn local_tasks_are_polled_after_tick() {
tx.send(oneshot_rx).unwrap(); tx.send(oneshot_rx).unwrap();
} }
time::delay_for(Duration::from_millis(100)).await; time::sleep(Duration::from_millis(100)).await;
for tx in oneshots.drain(..) { for tx in oneshots.drain(..) {
tx.send(()).unwrap(); tx.send(()).unwrap();
} }
time::delay_for(Duration::from_millis(300)).await; time::sleep(Duration::from_millis(300)).await;
let rx1 = RX1.load(SeqCst); let rx1 = RX1.load(SeqCst);
let rx2 = RX2.load(SeqCst); let rx2 = RX2.load(SeqCst);
println!("EXPECT = {}; RX1 = {}; RX2 = {}", EXPECTED, rx1, rx2); println!("EXPECT = {}; RX1 = {}; RX2 = {}", EXPECTED, rx1, rx2);
+16 -16
View File
@@ -26,7 +26,7 @@ async fn immediate_delay() {
let now = Instant::now(); let now = Instant::now();
// Ready! // Ready!
time::delay_until(now).await; time::sleep_until(now).await;
assert_elapsed!(now, 0); assert_elapsed!(now, 0);
} }
@@ -37,7 +37,7 @@ async fn delayed_delay_level_0() {
for &i in &[1, 10, 60] { for &i in &[1, 10, 60] {
let now = Instant::now(); let now = Instant::now();
time::delay_until(now + ms(i)).await; time::sleep_until(now + ms(i)).await;
assert_elapsed!(now, i); assert_elapsed!(now, i);
} }
@@ -51,7 +51,7 @@ async fn sub_ms_delayed_delay() {
let now = Instant::now(); let now = Instant::now();
let deadline = now + ms(1) + Duration::new(0, 1); let deadline = now + ms(1) + Duration::new(0, 1);
time::delay_until(deadline).await; time::sleep_until(deadline).await;
assert_elapsed!(now, 1); assert_elapsed!(now, 1);
} }
@@ -61,10 +61,10 @@ async fn sub_ms_delayed_delay() {
async fn delayed_delay_wrapping_level_0() { async fn delayed_delay_wrapping_level_0() {
time::pause(); time::pause();
time::delay_for(ms(5)).await; time::sleep(ms(5)).await;
let now = Instant::now(); let now = Instant::now();
time::delay_until(now + ms(60)).await; time::sleep_until(now + ms(60)).await;
assert_elapsed!(now, 60); assert_elapsed!(now, 60);
} }
@@ -75,7 +75,7 @@ async fn reset_future_delay_before_fire() {
let now = Instant::now(); let now = Instant::now();
let mut delay = task::spawn(time::delay_until(now + ms(100))); let mut delay = task::spawn(time::sleep_until(now + ms(100)));
assert_pending!(delay.poll()); assert_pending!(delay.poll());
let mut delay = delay.into_inner(); let mut delay = delay.into_inner();
@@ -92,7 +92,7 @@ async fn reset_past_delay_before_turn() {
let now = Instant::now(); let now = Instant::now();
let mut delay = task::spawn(time::delay_until(now + ms(100))); let mut delay = task::spawn(time::sleep_until(now + ms(100)));
assert_pending!(delay.poll()); assert_pending!(delay.poll());
let mut delay = delay.into_inner(); let mut delay = delay.into_inner();
@@ -109,12 +109,12 @@ async fn reset_past_delay_before_fire() {
let now = Instant::now(); let now = Instant::now();
let mut delay = task::spawn(time::delay_until(now + ms(100))); let mut delay = task::spawn(time::sleep_until(now + ms(100)));
assert_pending!(delay.poll()); assert_pending!(delay.poll());
let mut delay = delay.into_inner(); let mut delay = delay.into_inner();
time::delay_for(ms(10)).await; time::sleep(ms(10)).await;
delay.reset(now + ms(80)); delay.reset(now + ms(80));
delay.await; delay.await;
@@ -127,7 +127,7 @@ async fn reset_future_delay_after_fire() {
time::pause(); time::pause();
let now = Instant::now(); let now = Instant::now();
let mut delay = time::delay_until(now + ms(100)); let mut delay = time::sleep_until(now + ms(100));
(&mut delay).await; (&mut delay).await;
assert_elapsed!(now, 100); assert_elapsed!(now, 100);
@@ -143,10 +143,10 @@ async fn reset_delay_to_past() {
let now = Instant::now(); let now = Instant::now();
let mut delay = task::spawn(time::delay_until(now + ms(100))); let mut delay = task::spawn(time::sleep_until(now + ms(100)));
assert_pending!(delay.poll()); assert_pending!(delay.poll());
time::delay_for(ms(50)).await; time::sleep(ms(50)).await;
assert!(!delay.is_woken()); assert!(!delay.is_woken());
@@ -164,7 +164,7 @@ fn creating_delay_outside_of_context() {
// This creates a delay outside of the context of a mock timer. This tests // This creates a delay outside of the context of a mock timer. This tests
// that it will panic. // that it will panic.
let _fut = time::delay_until(now + ms(500)); let _fut = time::sleep_until(now + ms(500));
} }
#[should_panic] #[should_panic]
@@ -172,7 +172,7 @@ fn creating_delay_outside_of_context() {
async fn greater_than_max() { async fn greater_than_max() {
const YR_5: u64 = 5 * 365 * 24 * 60 * 60 * 1000; const YR_5: u64 = 5 * 365 * 24 * 60 * 60 * 1000;
time::delay_until(Instant::now() + ms(YR_5)).await; time::sleep_until(Instant::now() + ms(YR_5)).await;
} }
const NUM_LEVELS: usize = 6; const NUM_LEVELS: usize = 6;
@@ -182,13 +182,13 @@ const MAX_DURATION: u64 = (1 << (6 * NUM_LEVELS)) - 1;
#[tokio::test] #[tokio::test]
async fn exactly_max() { async fn exactly_max() {
// TODO: this should not panic but `time::ms()` is acting up // TODO: this should not panic but `time::ms()` is acting up
time::delay_for(ms(MAX_DURATION)).await; time::sleep(ms(MAX_DURATION)).await;
} }
#[tokio::test] #[tokio::test]
async fn no_out_of_bounds_close_to_max() { async fn no_out_of_bounds_close_to_max() {
time::pause(); time::pause();
time::delay_for(ms(MAX_DURATION - 1)).await; time::sleep(ms(MAX_DURATION - 1)).await;
} }
fn ms(n: u64) -> Duration { fn ms(n: u64) -> Duration {
+37 -37
View File
@@ -2,7 +2,7 @@
#![warn(rust_2018_idioms)] #![warn(rust_2018_idioms)]
#![cfg(feature = "full")] #![cfg(feature = "full")]
use tokio::time::{self, delay_for, DelayQueue, Duration, Instant}; use tokio::time::{self, sleep, DelayQueue, Duration, Instant};
use tokio_test::{assert_ok, assert_pending, assert_ready, task}; use tokio_test::{assert_ok, assert_pending, assert_ready, task};
macro_rules! poll { macro_rules! poll {
@@ -28,7 +28,7 @@ async fn single_immediate_delay() {
let _key = queue.insert_at("foo", Instant::now()); let _key = queue.insert_at("foo", Instant::now());
// Advance time by 1ms to handle thee rounding // Advance time by 1ms to handle thee rounding
delay_for(ms(1)).await; sleep(ms(1)).await;
assert_ready_ok!(poll!(queue)); assert_ready_ok!(poll!(queue));
@@ -46,7 +46,7 @@ async fn multi_immediate_delays() {
let _k = queue.insert_at("2", Instant::now()); let _k = queue.insert_at("2", Instant::now());
let _k = queue.insert_at("3", Instant::now()); let _k = queue.insert_at("3", Instant::now());
delay_for(ms(1)).await; sleep(ms(1)).await;
let mut res = vec![]; let mut res = vec![];
@@ -74,11 +74,11 @@ async fn single_short_delay() {
assert_pending!(poll!(queue)); assert_pending!(poll!(queue));
delay_for(ms(1)).await; sleep(ms(1)).await;
assert!(!queue.is_woken()); assert!(!queue.is_woken());
delay_for(ms(5)).await; sleep(ms(5)).await;
assert!(queue.is_woken()); assert!(queue.is_woken());
@@ -107,7 +107,7 @@ async fn multi_delay_at_start() {
assert!(!queue.is_woken()); assert!(!queue.is_woken());
for elapsed in 0..1200 { for elapsed in 0..1200 {
delay_for(ms(1)).await; sleep(ms(1)).await;
let elapsed = elapsed + 1; let elapsed = elapsed + 1;
if delays.contains(&elapsed) { if delays.contains(&elapsed) {
@@ -130,7 +130,7 @@ async fn insert_in_past_fires_immediately() {
let mut queue = task::spawn(DelayQueue::new()); let mut queue = task::spawn(DelayQueue::new());
let now = Instant::now(); let now = Instant::now();
delay_for(ms(10)).await; sleep(ms(10)).await;
queue.insert_at("foo", now); queue.insert_at("foo", now);
@@ -150,7 +150,7 @@ async fn remove_entry() {
let entry = queue.remove(&key); let entry = queue.remove(&key);
assert_eq!(entry.into_inner(), "foo"); assert_eq!(entry.into_inner(), "foo");
delay_for(ms(10)).await; sleep(ms(10)).await;
let entry = assert_ready!(poll!(queue)); let entry = assert_ready!(poll!(queue));
assert!(entry.is_none()); assert!(entry.is_none());
@@ -166,19 +166,19 @@ async fn reset_entry() {
let key = queue.insert_at("foo", now + ms(5)); let key = queue.insert_at("foo", now + ms(5));
assert_pending!(poll!(queue)); assert_pending!(poll!(queue));
delay_for(ms(1)).await; sleep(ms(1)).await;
queue.reset_at(&key, now + ms(10)); queue.reset_at(&key, now + ms(10));
assert_pending!(poll!(queue)); assert_pending!(poll!(queue));
delay_for(ms(7)).await; sleep(ms(7)).await;
assert!(!queue.is_woken()); assert!(!queue.is_woken());
assert_pending!(poll!(queue)); assert_pending!(poll!(queue));
delay_for(ms(3)).await; sleep(ms(3)).await;
assert!(queue.is_woken()); assert!(queue.is_woken());
@@ -197,16 +197,16 @@ async fn reset_much_later() {
let mut queue = task::spawn(DelayQueue::new()); let mut queue = task::spawn(DelayQueue::new());
let now = Instant::now(); let now = Instant::now();
delay_for(ms(1)).await; sleep(ms(1)).await;
let key = queue.insert_at("foo", now + ms(200)); let key = queue.insert_at("foo", now + ms(200));
assert_pending!(poll!(queue)); assert_pending!(poll!(queue));
delay_for(ms(3)).await; sleep(ms(3)).await;
queue.reset_at(&key, now + ms(5)); queue.reset_at(&key, now + ms(5));
delay_for(ms(20)).await; sleep(ms(20)).await;
assert!(queue.is_woken()); assert!(queue.is_woken());
} }
@@ -219,21 +219,21 @@ async fn reset_twice() {
let mut queue = task::spawn(DelayQueue::new()); let mut queue = task::spawn(DelayQueue::new());
let now = Instant::now(); let now = Instant::now();
delay_for(ms(1)).await; sleep(ms(1)).await;
let key = queue.insert_at("foo", now + ms(200)); let key = queue.insert_at("foo", now + ms(200));
assert_pending!(poll!(queue)); assert_pending!(poll!(queue));
delay_for(ms(3)).await; sleep(ms(3)).await;
queue.reset_at(&key, now + ms(50)); queue.reset_at(&key, now + ms(50));
delay_for(ms(20)).await; sleep(ms(20)).await;
queue.reset_at(&key, now + ms(40)); queue.reset_at(&key, now + ms(40));
delay_for(ms(20)).await; sleep(ms(20)).await;
assert!(queue.is_woken()); assert!(queue.is_woken());
} }
@@ -246,7 +246,7 @@ async fn remove_expired_item() {
let now = Instant::now(); let now = Instant::now();
delay_for(ms(10)).await; sleep(ms(10)).await;
let key = queue.insert_at("foo", now); let key = queue.insert_at("foo", now);
@@ -272,7 +272,7 @@ async fn expires_before_last_insert() {
assert_pending!(poll!(queue)); assert_pending!(poll!(queue));
delay_for(ms(600)).await; sleep(ms(600)).await;
assert!(queue.is_woken()); assert!(queue.is_woken());
@@ -297,18 +297,18 @@ async fn multi_reset() {
queue.reset_at(&two, now + ms(350)); queue.reset_at(&two, now + ms(350));
queue.reset_at(&one, now + ms(400)); queue.reset_at(&one, now + ms(400));
delay_for(ms(310)).await; sleep(ms(310)).await;
assert_pending!(poll!(queue)); assert_pending!(poll!(queue));
delay_for(ms(50)).await; sleep(ms(50)).await;
let entry = assert_ready_ok!(poll!(queue)); let entry = assert_ready_ok!(poll!(queue));
assert_eq!(*entry.get_ref(), "two"); assert_eq!(*entry.get_ref(), "two");
assert_pending!(poll!(queue)); assert_pending!(poll!(queue));
delay_for(ms(50)).await; sleep(ms(50)).await;
let entry = assert_ready_ok!(poll!(queue)); let entry = assert_ready_ok!(poll!(queue));
assert_eq!(*entry.get_ref(), "one"); assert_eq!(*entry.get_ref(), "one");
@@ -332,7 +332,7 @@ async fn expire_first_key_when_reset_to_expire_earlier() {
queue.reset_at(&one, now + ms(100)); queue.reset_at(&one, now + ms(100));
delay_for(ms(100)).await; sleep(ms(100)).await;
assert!(queue.is_woken()); assert!(queue.is_woken());
@@ -355,7 +355,7 @@ async fn expire_second_key_when_reset_to_expire_earlier() {
queue.reset_at(&two, now + ms(100)); queue.reset_at(&two, now + ms(100));
delay_for(ms(100)).await; sleep(ms(100)).await;
assert!(queue.is_woken()); assert!(queue.is_woken());
@@ -377,7 +377,7 @@ async fn reset_first_expiring_item_to_expire_later() {
assert_pending!(poll!(queue)); assert_pending!(poll!(queue));
queue.reset_at(&one, now + ms(300)); queue.reset_at(&one, now + ms(300));
delay_for(ms(250)).await; sleep(ms(250)).await;
assert!(queue.is_woken()); assert!(queue.is_woken());
@@ -399,11 +399,11 @@ async fn insert_before_first_after_poll() {
let _two = queue.insert_at("two", now + ms(100)); let _two = queue.insert_at("two", now + ms(100));
delay_for(ms(99)).await; sleep(ms(99)).await;
assert!(!queue.is_woken()); assert!(!queue.is_woken());
delay_for(ms(1)).await; sleep(ms(1)).await;
assert!(queue.is_woken()); assert!(queue.is_woken());
@@ -425,7 +425,7 @@ async fn insert_after_ready_poll() {
assert_pending!(poll!(queue)); assert_pending!(poll!(queue));
delay_for(ms(100)).await; sleep(ms(100)).await;
assert!(queue.is_woken()); assert!(queue.is_woken());
@@ -456,7 +456,7 @@ async fn reset_later_after_slot_starts() {
assert_pending!(poll!(queue)); assert_pending!(poll!(queue));
delay_for(ms(80)).await; sleep(ms(80)).await;
assert!(!queue.is_woken()); assert!(!queue.is_woken());
@@ -471,10 +471,10 @@ async fn reset_later_after_slot_starts() {
assert_pending!(poll!(queue)); assert_pending!(poll!(queue));
delay_for(ms(39)).await; sleep(ms(39)).await;
assert!(!queue.is_woken()); assert!(!queue.is_woken());
delay_for(ms(1)).await; sleep(ms(1)).await;
assert!(queue.is_woken()); assert!(queue.is_woken());
let entry = assert_ready_ok!(poll!(queue)).into_inner(); let entry = assert_ready_ok!(poll!(queue)).into_inner();
@@ -494,7 +494,7 @@ async fn reset_inserted_expired() {
assert_eq!(1, queue.len()); assert_eq!(1, queue.len());
delay_for(ms(200)).await; sleep(ms(200)).await;
let entry = assert_ready_ok!(poll!(queue)).into_inner(); let entry = assert_ready_ok!(poll!(queue)).into_inner();
assert_eq!(entry, "foo"); assert_eq!(entry, "foo");
@@ -514,7 +514,7 @@ async fn reset_earlier_after_slot_starts() {
assert_pending!(poll!(queue)); assert_pending!(poll!(queue));
delay_for(ms(80)).await; sleep(ms(80)).await;
assert!(!queue.is_woken()); assert!(!queue.is_woken());
@@ -529,10 +529,10 @@ async fn reset_earlier_after_slot_starts() {
assert_pending!(poll!(queue)); assert_pending!(poll!(queue));
delay_for(ms(39)).await; sleep(ms(39)).await;
assert!(!queue.is_woken()); assert!(!queue.is_woken());
delay_for(ms(1)).await; sleep(ms(1)).await;
assert!(queue.is_woken()); assert!(queue.is_woken());
let entry = assert_ready_ok!(poll!(queue)).into_inner(); let entry = assert_ready_ok!(poll!(queue)).into_inner();
@@ -551,7 +551,7 @@ async fn insert_in_past_after_poll_fires_immediately() {
assert_pending!(poll!(queue)); assert_pending!(poll!(queue));
delay_for(ms(80)).await; sleep(ms(80)).await;
assert!(!queue.is_woken()); assert!(!queue.is_woken());
queue.insert_at("bar", now + ms(40)); queue.insert_at("bar", now + ms(40));
+3 -3
View File
@@ -15,7 +15,7 @@ fn timer_with_threaded_runtime() {
rt.spawn(async move { rt.spawn(async move {
let when = Instant::now() + Duration::from_millis(100); let when = Instant::now() + Duration::from_millis(100);
delay_until(when).await; sleep_until(when).await;
assert!(Instant::now() >= when); assert!(Instant::now() >= when);
tx.send(()).unwrap(); tx.send(()).unwrap();
@@ -38,7 +38,7 @@ fn timer_with_basic_scheduler() {
rt.block_on(async move { rt.block_on(async move {
let when = Instant::now() + Duration::from_millis(100); let when = Instant::now() + Duration::from_millis(100);
delay_until(when).await; sleep_until(when).await;
assert!(Instant::now() >= when); assert!(Instant::now() >= when);
tx.send(()).unwrap(); tx.send(()).unwrap();
@@ -72,7 +72,7 @@ async fn starving() {
} }
let when = Instant::now() + Duration::from_millis(20); let when = Instant::now() + Duration::from_millis(20);
let starve = Starve(delay_until(when), 0); let starve = Starve(sleep_until(when), 0);
starve.await; starve.await;
assert!(Instant::now() >= when); assert!(Instant::now() >= when);