From 3b6fe86828a28de2b1dbec191c952d62bade4fbe Mon Sep 17 00:00:00 2001 From: Seth Brown Date: Mon, 5 Apr 2021 12:25:41 -0600 Subject: [PATCH 01/17] time: allow users to specify `Interval` behavior when delayed Occasionally, `tokio::time::Interval` may be delayed from ticking by a blocked executor. By default, `Interval` continues to schedule ticks normally, which causes a burst of ticks until it is "caught up" in time where it should be. This behavior is not always desired, however, so this commit adds the `MissedTickBehavior` enum to the `time` module to allow users to specify what behavior they'd like `Interval` to exhibit in such situations. Closes #3574 --- tokio/src/time/interval.rs | 353 +++++++++++++++++++++++++++++++---- tokio/src/time/mod.rs | 28 +-- tokio/tests/time_interval.rs | 171 ++++++++++++++--- 3 files changed, 483 insertions(+), 69 deletions(-) diff --git a/tokio/src/time/interval.rs b/tokio/src/time/interval.rs index 4b1c6f6dfda..9140a9241c5 100644 --- a/tokio/src/time/interval.rs +++ b/tokio/src/time/interval.rs @@ -1,17 +1,20 @@ use crate::future::poll_fn; use crate::time::{sleep_until, Duration, Instant, Sleep}; -use std::future::Future; use std::pin::Pin; use std::task::{Context, Poll}; +use std::{convert::TryInto, future::Future}; -/// Creates new `Interval` that yields with interval of `duration`. The first -/// tick completes immediately. +/// Creates new [`Interval`] that yields with interval of `period`. The first +/// tick completes immediately. The [`MissedTickBehavior`] is the +/// [default one](MissedTickBehavior::default), which is +/// [`Burst`](MissedTickBehavior::Burst). /// -/// An interval will tick indefinitely. At any time, the `Interval` value can be -/// dropped. This cancels the interval. +/// An interval will tick indefinitely. At any time, the [`Interval`] value can +/// be dropped. This cancels the interval. /// -/// This function is equivalent to `interval_at(Instant::now(), period)`. +/// This function is equivalent to +/// [`interval_at(Instant::now(), period)`](interval_at). /// /// # Panics /// @@ -26,9 +29,9 @@ use std::task::{Context, Poll}; /// async fn main() { /// let mut interval = time::interval(Duration::from_millis(10)); /// -/// interval.tick().await; -/// interval.tick().await; -/// interval.tick().await; +/// interval.tick().await; // ticks immediately +/// interval.tick().await; // ticks after 10ms +/// interval.tick().await; // ticks after 10ms /// /// // approximately 20ms have elapsed. /// } @@ -37,9 +40,9 @@ use std::task::{Context, Poll}; /// A simple example using `interval` to execute a task every two seconds. /// /// 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 -/// 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 [`sleep`], the task /// would only be executed once every three seconds, and not every two @@ -64,17 +67,23 @@ use std::task::{Context, Poll}; /// ``` /// /// [`sleep`]: crate::time::sleep() +/// [`.tick().await`]: Interval::tick pub fn interval(period: Duration) -> Interval { assert!(period > Duration::new(0, 0), "`period` must be non-zero."); interval_at(Instant::now(), period) } -/// Creates new `Interval` that yields with interval of `period` with the -/// first tick completing at `start`. +/// Creates new [`Interval`] that yields with interval of `period` with the +/// first tick completing at `start`. The [`MissedTickBehavior`] is the +/// [default one](MissedTickBehavior::default), which is +/// [`Burst`](MissedTickBehavior::Burst). /// -/// An interval will tick indefinitely. At any time, the `Interval` value can be -/// dropped. This cancels the interval. +/// An interval will tick indefinitely. At any time, the [`Interval`] value can +/// be dropped. This cancels the interval. +/// +/// This function is equivalent to +/// [`interval_with_missed_tick_behavior_at(start, period, Default::default())`](interval_with_missed_tick_behavior_at) /// /// # Panics /// @@ -90,9 +99,9 @@ pub fn interval(period: Duration) -> Interval { /// let start = Instant::now() + Duration::from_millis(50); /// let mut interval = interval_at(start, Duration::from_millis(10)); /// -/// interval.tick().await; -/// interval.tick().await; -/// interval.tick().await; +/// interval.tick().await; // ticks after 50ms +/// interval.tick().await; // ticks after 10ms +/// interval.tick().await; // ticks after 10ms /// /// // approximately 70ms have elapsed. /// } @@ -100,22 +109,265 @@ pub fn interval(period: Duration) -> Interval { pub fn interval_at(start: Instant, period: Duration) -> Interval { assert!(period > Duration::new(0, 0), "`period` must be non-zero."); + interval_with_missed_tick_behavior_at(start, period, Default::default()) +} + +/// Creates new [`Interval`] with a specific [`MissedTickBehavior`] that yields +/// with interval of `period`. The first tick completes immediately. +/// +/// An interval will tick indefinitely. At any time, the [`Interval`] value can +/// be dropped. This cancels the interval. +/// +/// This function is equivalent to +/// [`interval_with_missed_tick_behavior_at(Instant::now(), period, missed_tick_behavior)`](interval_with_missed_tick_behavior_at) +/// +/// # Panics +/// +/// This function panics if `period` is zero. +/// +/// # Examples +/// +/// ``` +/// use tokio::time::{ +/// interval_with_missed_tick_behavior, +/// sleep, +/// Duration, +/// MissedTickBehavior, +/// }; +/// +/// #[tokio::main] +/// async fn main() { +/// let mut interval = interval_with_missed_tick_behavior( +/// Duration::from_millis(10), +/// MissedTickBehavior::Skip, +/// ); +/// +/// interval.tick().await; // ticks immediately +/// sleep(Duration::from_millis(25)).await; // simulating executor getting blocked +/// interval.tick().await; // ticks immediately, yielding an `Instant` 10ms after the starting tick +/// interval.tick().await; // ticks after 5ms, yielding an `Instant` 30ms after the starting tick +/// +/// // approximately 30ms have elapsed. +/// } +/// ``` +pub fn interval_with_missed_tick_behavior( + period: Duration, + missed_tick_behavior: MissedTickBehavior, +) -> Interval { + assert!(period > Duration::new(0, 0), "`period` must be non-zero."); + + interval_with_missed_tick_behavior_at(Instant::now(), period, missed_tick_behavior) +} + +/// Creates new [`Interval`] with a specific [`MissedTickBehavior`] that yields +/// with interval of `period`. The first tick completes at `start`. +/// +/// An interval will tick indefinitely. At any time, the [`Interval`] value can +/// be dropped. This cancels the interval. +/// +/// # Panics +/// +/// This function panics if `period` is zero. +/// +/// # Examples +/// +/// ``` +/// use tokio::time::{ +/// interval_with_missed_tick_behavior_at, +/// sleep, +/// Duration, +/// Instant, +/// MissedTickBehavior +/// }; +/// +/// #[tokio::main] +/// async fn main() { +/// let start = Instant::now() + Duration::from_millis(50); +/// let mut interval = interval_with_missed_tick_behavior_at( +/// start, +/// Duration::from_millis(10), +/// MissedTickBehavior::Skip, +/// ); +/// +/// interval.tick().await; // ticks after 50ms +/// sleep(Duration::from_millis(25)).await; // simulating executor getting blocked +/// interval.tick().await; // ticks immediately, yielding an `Instant` 10ms after the starting tick +/// interval.tick().await; // ticks after 5ms, yielding an `Instant` 30ms after the starting tick +/// +/// // approximately 30ms have elapsed. +/// } +/// ``` +pub fn interval_with_missed_tick_behavior_at( + start: Instant, + period: Duration, + missed_tick_behavior: MissedTickBehavior, +) -> Interval { + assert!(period > Duration::new(0, 0), "`period` must be non-zero."); + Interval { delay: Box::pin(sleep_until(start)), period, + missed_tick_behavior, } } -/// Interval returned by [`interval`](interval) and [`interval_at`](interval_at). +/// Defines the behavior of an [`Interval`] when it misses a tick. +/// +/// Occasionally, the executor may be blocked, and as a result, [`Interval`] +/// misses a tick. By default, when this happens, [`Interval`] fires ticks +/// as quickly as it can until it is back to where it should be. However, +/// this is not always the desired behavior when ticks are missed. +/// `MissedTickBehavior` allows users to specify which behavior they want +/// [`Interval`] to exhibit. Each variant represents a different strategy. +/// +/// Because the executor cannot guarantee exect precision with +/// timers, these strategies will only apply when the +/// error in time is greater than 5 milliseconds. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum MissedTickBehavior { + /// Tick as fast as possible until caught up. + /// + /// When this strategy is used, after regaining control, [`Interval`] ticks + /// as fast as it can until it is caught up to where it should be had the + /// executor not been blocked. The [`Instant`]s yielded by + /// [`tick`](Interval::tick()) are the same as they would have been if the executor had not + /// been blocked. + /// + /// This would look something like this: + /// ```text + /// Expected ticks: | 1 | 2 | 3 | 4 | 5 | 6 | + /// Actual ticks: | work -----| delay | work | work | work -| work -----| + // Poll behavior: | | | | | | | | + // | | | | | | | | + // Ready(s) | | Ready(s + 2p) | | | | + // Pending | Ready(s + 3p) | | | + // Ready(s + p) Ready(s + 4p) | | + // Ready(s + 5p) | + // Ready(s + 6p) + // * Where `s` is the start time and `p` is the period + /// ``` + /// + /// This is the default behavior when [`Interval`] is created with + /// [`interval`] and [`interval_at`]. + /// + /// Note: this is the behavior that [`Interval`] exhibited in previous + /// versions of Tokio. + Burst, + + /// Delay missed ticks to happen at multiples of [`period`] from when + /// [`Interval`] regained control. + /// + /// When this strategy is used, after regaining control, [`Interval`] ticks + /// immediately, then schedules all future ticks to happen at a regular + /// [`period`] from the point when [`Interval`] regained control. + /// [`tick`] yields immediately with an [`Instant`] that represents the time + /// that the tick should have happened. All subsequent calls to + /// [`tick`] yield an [`Instant`] that is a multiple of + /// [`period`] away from the point that [`Interval`] regained control. + /// + /// This would look something like this: + /// ```text + /// Expected ticks: | 1 | 2 | 3 | 4 | 5 | 6 | + /// Actual ticks: | work -----| delay | work -----| work -----| work -----| + // Poll behavior: | | | | | | | | + // | | | | | | | | + // Ready(s) | | Ready(s + 2p) | | | | + // Pending | Pending | | | + // Ready(s + p) Ready(s + 2p + d) | | + // Ready(s + 3p + d) | + // Ready(s + 4p + d) + // * Where `s` is the start time, `p` is the period, and `d` is the delay + /// ``` + /// + /// Note that as a result, the ticks are no longer guaranteed to happen at + /// a multiple of [`period`] from `delay`. + /// + /// [`period`]: Interval::period + /// [`tick`]: Interval::tick + Delay, + + /// Skip the missed ticks and tick on the next multiple of [`period`]. + /// + /// When this strategy is used, after regaining control, [`Interval`] ticks + /// immediately, then schedules the next tick on the closest multiple of + /// [`period`] from `delay`. Thus, the yielded value from + /// [`tick`](Interval::tick) is an [`Instant`] that is some multiple of + /// [`period`] from `start`. However, that yielded [`Instant`] is not + /// guarenteed to be exactly one multiple of [`period`] from the tick that + /// got blocked. + /// + /// This would look something like this: + /// ```text + /// Expected ticks: | 1 | 2 | 3 | 4 | 5 | 6 | + /// Actual ticks: | work -----| delay | work ---| work -----| work -----| + // Poll behavior: | | | | | | | + // | | | | | | | + // Ready(s) | | Ready(s + 2p) | | | + // Pending | Ready(s + 4p) | | + // Ready(s + p) Ready(s + 5p) | + // Ready(s + 6p) + // * Where `s` is the start time and `p` is the period + /// ``` + /// + /// [`period`]: Interval::period + Skip, +} + +impl MissedTickBehavior { + /// Determine when the next tick should happen. + fn next_timeout(&self, timeout: Instant, now: Instant, period: Duration) -> Instant { + match self { + Self::Burst => timeout + period, + Self::Delay => now + period, + Self::Skip => { + now + period + - Duration::from_nanos( + ((now - timeout).as_nanos() % period.as_nanos()) + .try_into() + // This operation is practically guaranteed not to + // fail, as in order for it to fail, `period` would + // have to be longer than `now - timeout`, and both + // would have to be longer than 584 years. + // + // If it did fail, there's not a good way to pass + // the error along to the user, so we just panic. + .expect( + "too much time has elapsed since the interval was supposed to tick", + ), + ) + } + } + } +} + +impl Default for MissedTickBehavior { + /// Returns [`MissedTickBehavior::Burst`]. + /// + /// For most usecases, the [`Burst`] strategy is what is desired. + /// Additionally, to preserve backwards compatibility, the [`Burst`] + /// strategy must be the default. For these reasons, + /// [`MissedTickBehavior::Burst`] is the default for + /// [`MissedTickBehavior`]. See [`Burst`] for more details. + /// + /// [`Burst`]: MissedTickBehavior::Burst + fn default() -> Self { + Self::Burst + } +} + +/// Interval returned by [`interval`], [`interval_at`], +/// [`interval_with_missed_tick_behavior`], and +/// [`interval_with_missed_tick_behavior_at`]. /// /// This type allows you to wait on a sequence of instants with a certain -/// duration between each instant. Unlike calling [`sleep`](crate::time::sleep) -/// in a loop, this lets you count the time spent between the calls to `sleep` -/// as well. +/// duration between each instant. Unlike calling [`sleep`] in a loop, this lets +/// you count the time spent between the calls to [`sleep`] as well. /// -/// An `Interval` can be turned into a `Stream` with [`IntervalStream`]. +/// An `Interval` can be turned into a [`Stream`] with [`IntervalStream`]. /// -/// [`IntervalStream`]: https://docs.rs/tokio-stream/0.1/tokio_stream/wrappers/struct.IntervalStream.html +/// [`IntervalStream`]: https://docs.rs/tokio-stream/latest/tokio_stream/wrappers/struct.IntervalStream.html +/// [`sleep`]: crate::time::sleep +/// [`Stream`]: std::stream::Stream #[derive(Debug)] pub struct Interval { /// Future that completes the next time the `Interval` yields a value. @@ -123,6 +375,10 @@ pub struct Interval { /// The duration between values yielded by `Interval`. period: Duration, + + /// The strategy `Interval` should use when the executor gets blocked and a + /// tick is missed. + missed_tick_behavior: MissedTickBehavior, } impl Interval { @@ -159,22 +415,55 @@ impl Interval { /// /// When this method returns `Poll::Pending`, the current task is scheduled /// to receive a wakeup when the instant has elapsed. Note that on multiple - /// calls to `poll_tick`, only the `Waker` from the `Context` passed to the - /// most recent call is scheduled to receive a wakeup. + /// calls to `poll_tick`, only the [`Waker`](std::task::Waker) from the + /// [`Context`] passed to the most recent call is scheduled to receive a + /// wakeup. pub fn poll_tick(&mut self, cx: &mut Context<'_>) -> Poll { // Wait for the delay to be done ready!(Pin::new(&mut self.delay).poll(cx)); - // Get the `now` by looking at the `delay` deadline - let now = self.delay.deadline(); + // Get the time at which the `delay` was supposed to complete + let timeout = self.delay.deadline(); + + let now = Instant::now(); + + // If the executor was not blocked, and thus we are being called + // before the next tick is due, just schedule the next tick normally, + // one `period` after `scheduled_timeout`, when the last tick went + // off + // + // However, if a tick took excessively long and we are now behind, + // schedule the next tick according to how the user specified with + // `MissedTickBehavior` + let next = if now > timeout + Duration::from_millis(5) { + self.missed_tick_behavior + .next_timeout(timeout, now, self.period) + } else { + timeout + self.period + }; - // The next interval value is `duration` after the one that just - // yielded. - let next = now + self.period; self.delay.as_mut().reset(next); // Return the current instant - Poll::Ready(now) + Poll::Ready(timeout) + } + + /// Returns the [`MissedTickBehavior`] strategy that is currently being + /// used. + pub fn missed_tick_behavior(&self) -> MissedTickBehavior { + self.missed_tick_behavior + } + + /// Sets the [`MissedTickBehavior`] strategy that should be used. + pub fn set_missed_tick_behavior(&mut self, behavior: MissedTickBehavior) { + self.missed_tick_behavior = behavior; + } + + /// Resets the [`MissedTickBehavior`] strategy that should be used to the + /// [default one](MissedTickBehavior::default), which is + /// [`Burst`](MissedTickBehavior::Burst). + pub fn reset_missed_tick_behavior(&mut self) { + self.missed_tick_behavior = Default::default(); } /// Returns the period of the interval. diff --git a/tokio/src/time/mod.rs b/tokio/src/time/mod.rs index 98bb2af1070..b299cf70b75 100644 --- a/tokio/src/time/mod.rs +++ b/tokio/src/time/mod.rs @@ -3,21 +3,21 @@ //! This module provides a number of types for executing code after a set period //! of time. //! -//! * `Sleep` is a future that does no work and completes at a specific `Instant` +//! * [`Sleep`] is a future that does no work and completes at a specific [`Instant`] //! in time. //! -//! * `Interval` is a stream yielding a value at a fixed period. It is -//! initialized with a `Duration` and repeatedly yields each time the duration +//! * [`Interval`] is a stream yielding a value at a fixed period. It is +//! initialized with a [`Duration`] and repeatedly yields each time the duration //! elapses. //! -//! * `Timeout`: Wraps a future or stream, setting an upper bound to the amount +//! * [`Timeout`]: Wraps a future or stream, setting an upper bound to the amount //! of time it is allowed to execute. If the future or stream does not //! complete in time, then it is canceled and an error is returned. //! //! These types are sufficient for handling a large number of scenarios //! involving time. //! -//! These types must be used from within the context of the `Runtime`. +//! These types must be used from within the context of the [`Runtime`](crate::runtime::Runtime). //! //! # Examples //! @@ -52,11 +52,13 @@ //! # } //! ``` //! -//! A simple example using [`interval`] to execute a task every two seconds. +//! A simple example using [`interval`](self::interval::interval) to execute +//! a task every two seconds. //! -//! The difference between [`interval`] and [`sleep`] is that an [`interval`] -//! 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 +//! The difference between [`interval`](self::interval::interval) and +//! [`sleep`] is that an [`interval`](self::interval::interval) 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 //! if some time has passed between calls to `.tick().await`. //! //! If the tick in the example below was replaced with [`sleep`], the task @@ -80,9 +82,6 @@ //! } //! } //! ``` -//! -//! [`sleep`]: crate::time::sleep() -//! [`interval`]: crate::time::interval() mod clock; pub(crate) use self::clock::Clock; @@ -100,7 +99,10 @@ mod instant; pub use self::instant::Instant; mod interval; -pub use interval::{interval, interval_at, Interval}; +pub use interval::{ + interval, interval_at, interval_with_missed_tick_behavior, + interval_with_missed_tick_behavior_at, Interval, MissedTickBehavior, +}; mod timeout; #[doc(inline)] diff --git a/tokio/tests/time_interval.rs b/tokio/tests/time_interval.rs index a3c7f0874c6..f7fbb5e76c6 100644 --- a/tokio/tests/time_interval.rs +++ b/tokio/tests/time_interval.rs @@ -4,53 +4,176 @@ use tokio::time::{self, Duration, Instant}; use tokio_test::{assert_pending, assert_ready_eq, task}; -use std::future::Future; use std::task::Poll; +// Takes the `Interval` task, `start` variable, and optional time deltas +// For each time delta, it polls the `Interval` and asserts that the result is +// equal to `start` + the specific time delta. Then it asserts that the +// `Interval` is pending. +macro_rules! check_interval_poll { + ($i:ident, $start:ident, $($delta:expr),*$(,)?) => { + $( + assert_ready_eq!(poll_next(&mut $i), $start + ms($delta)); + )* + assert_pending!(poll_next(&mut $i)); + }; + ($i:ident, $start:ident) => { + check_interval_poll!($i, $start,); + }; +} + #[tokio::test] #[should_panic] async fn interval_zero_duration() { let _ = time::interval_at(Instant::now(), ms(0)); } -#[tokio::test] -async fn usage() { - time::pause(); - +// Expected ticks: | 1 | 2 | 3 | 4 | 5 | 6 | +// Actual ticks: | work -----| delay | work | work | work -| work -----| +// Poll behavior: | | | | | | | | +// | | | | | | | | +// Ready(s) | | Ready(s + 2p) | | | | +// Pending | Ready(s + 3p) | | | +// Ready(s + p) Ready(s + 4p) | | +// Ready(s + 5p) | +// Ready(s + 6p) +#[tokio::test(start_paused = true)] +async fn burst() { let start = Instant::now(); - // TODO: Skip this + // This is necessary because the timer is only so granular, and in order for + // all our ticks to resolve, the time needs to be 1ms ahead of what we + // expect, so that the runtime will see that it is time to resolve the timer time::advance(ms(1)).await; let mut i = task::spawn(time::interval_at(start, ms(300))); - assert_ready_eq!(poll_next(&mut i), start); - assert_pending!(poll_next(&mut i)); + check_interval_poll!(i, start, 0); time::advance(ms(100)).await; - assert_pending!(poll_next(&mut i)); + check_interval_poll!(i, start); time::advance(ms(200)).await; - assert_ready_eq!(poll_next(&mut i), start + ms(300)); - assert_pending!(poll_next(&mut i)); + check_interval_poll!(i, start, 300); + + time::advance(ms(650)).await; + check_interval_poll!(i, start, 600, 900); + + time::advance(ms(200)).await; + check_interval_poll!(i, start); + + time::advance(ms(100)).await; + check_interval_poll!(i, start, 1200); + + time::advance(ms(250)).await; + check_interval_poll!(i, start, 1500); + + time::advance(ms(300)).await; + check_interval_poll!(i, start, 1800); +} + +// Expected ticks: | 1 | 2 | 3 | 4 | 5 | 6 | +// Actual ticks: | work -----| delay | work -----| work -----| work -----| +// Poll behavior: | | | | | | | | +// | | | | | | | | +// Ready(s) | | Ready(s + 2p) | | | | +// Pending | Pending | | | +// Ready(s + p) Ready(s + 2p + d) | | +// Ready(s + 3p + d) | +// Ready(s + 4p + d) +#[tokio::test(start_paused = true)] +async fn delay() { + let start = Instant::now(); + + // This is necessary because the timer is only so granular, and in order for + // all our ticks to resolve, the time needs to be 1ms ahead of what we + // expect, so that the runtime will see that it is time to resolve the timer + time::advance(ms(1)).await; + + let mut i = task::spawn(time::interval_with_missed_tick_behavior_at( + start, + ms(300), + time::MissedTickBehavior::Delay, + )); + + check_interval_poll!(i, start, 0); + + time::advance(ms(100)).await; + check_interval_poll!(i, start); + + time::advance(ms(200)).await; + check_interval_poll!(i, start, 300); + + time::advance(ms(650)).await; + check_interval_poll!(i, start, 600); + + time::advance(ms(100)).await; + check_interval_poll!(i, start); + + // We have to add one here for the same reason as is above. + // Because `Interval` has reset its timer according to `Instant::now()`, + // we have to go forward 1 more millisecond than is expected so that the + // runtime realizes that it's time to resolve the timer. + time::advance(ms(201)).await; + // We add one because when using the `Delay` behavior, `Interval` + // adds the `period` from `Instant::now()`, which will always be off by one + // because we have to advance time by 1 (see above). + check_interval_poll!(i, start, 1251); + + time::advance(ms(300)).await; + // Again, we add one. + check_interval_poll!(i, start, 1551); + + time::advance(ms(300)).await; + check_interval_poll!(i, start, 1851); +} + +// Expected ticks: | 1 | 2 | 3 | 4 | 5 | 6 | +// Actual ticks: | work -----| delay | work ---| work -----| work -----| +// Poll behavior: | | | | | | | +// | | | | | | | +// Ready(s) | | Ready(s + 2p) | | | +// Pending | Ready(s + 4p) | | +// Ready(s + p) Ready(s + 5p) | +// Ready(s + 6p) +#[tokio::test(start_paused = true)] +async fn skip() { + let start = Instant::now(); + + // This is necessary because the timer is only so granular, and in order for + // all our ticks to resolve, the time needs to be 1ms ahead of what we + // expect, so that the runtime will see that it is time to resolve the timer + time::advance(ms(1)).await; + + let mut i = task::spawn(time::interval_with_missed_tick_behavior_at( + start, + ms(300), + time::MissedTickBehavior::Skip, + )); + + check_interval_poll!(i, start, 0); + + time::advance(ms(100)).await; + check_interval_poll!(i, start); + + time::advance(ms(200)).await; + check_interval_poll!(i, start, 300); + + time::advance(ms(650)).await; + check_interval_poll!(i, start, 600); + + time::advance(ms(250)).await; + check_interval_poll!(i, start, 1200); - time::advance(ms(400)).await; - assert_ready_eq!(poll_next(&mut i), start + ms(600)); - assert_pending!(poll_next(&mut i)); + time::advance(ms(300)).await; + check_interval_poll!(i, start, 1500); - time::advance(ms(500)).await; - assert_ready_eq!(poll_next(&mut i), start + ms(900)); - assert_ready_eq!(poll_next(&mut i), start + ms(1200)); - assert_pending!(poll_next(&mut i)); + time::advance(ms(300)).await; + check_interval_poll!(i, start, 1800); } fn poll_next(interval: &mut task::Spawn) -> Poll { - interval.enter(|cx, mut interval| { - tokio::pin! { - let fut = interval.tick(); - } - fut.poll(cx) - }) + interval.enter(|cx, mut interval| interval.poll_tick(cx)) } fn ms(n: u64) -> Duration { From 46c2cbfdf4deb4cab3d7732baef2877439e629b8 Mon Sep 17 00:00:00 2001 From: Seth Brown Date: Fri, 23 Apr 2021 09:11:47 -0600 Subject: [PATCH 02/17] Fix broken docs --- tokio/src/time/interval.rs | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/tokio/src/time/interval.rs b/tokio/src/time/interval.rs index 9140a9241c5..52cdef4bbba 100644 --- a/tokio/src/time/interval.rs +++ b/tokio/src/time/interval.rs @@ -363,11 +363,10 @@ impl Default for MissedTickBehavior { /// duration between each instant. Unlike calling [`sleep`] in a loop, this lets /// you count the time spent between the calls to [`sleep`] as well. /// -/// An `Interval` can be turned into a [`Stream`] with [`IntervalStream`]. +/// An `Interval` can be turned into a `Stream` with [`IntervalStream`]. /// /// [`IntervalStream`]: https://docs.rs/tokio-stream/latest/tokio_stream/wrappers/struct.IntervalStream.html /// [`sleep`]: crate::time::sleep -/// [`Stream`]: std::stream::Stream #[derive(Debug)] pub struct Interval { /// Future that completes the next time the `Interval` yields a value. From 3149eeefe9e0234b6948edec0f613d2cc30bb4de Mon Sep 17 00:00:00 2001 From: Seth Brown Date: Fri, 23 Apr 2021 11:03:50 -0600 Subject: [PATCH 03/17] Fix erroneous doc link --- tokio/src/time/interval.rs | 19 ++++++++----------- tokio/src/time/mod.rs | 10 +++++----- 2 files changed, 13 insertions(+), 16 deletions(-) diff --git a/tokio/src/time/interval.rs b/tokio/src/time/interval.rs index 52cdef4bbba..0c317085893 100644 --- a/tokio/src/time/interval.rs +++ b/tokio/src/time/interval.rs @@ -254,16 +254,16 @@ pub enum MissedTickBehavior { /// versions of Tokio. Burst, - /// Delay missed ticks to happen at multiples of [`period`] from when + /// Delay missed ticks to happen at multiples of `period` from when /// [`Interval`] regained control. /// /// When this strategy is used, after regaining control, [`Interval`] ticks /// immediately, then schedules all future ticks to happen at a regular - /// [`period`] from the point when [`Interval`] regained control. + /// `period` from the point when [`Interval`] regained control. /// [`tick`] yields immediately with an [`Instant`] that represents the time /// that the tick should have happened. All subsequent calls to /// [`tick`] yield an [`Instant`] that is a multiple of - /// [`period`] away from the point that [`Interval`] regained control. + /// `period` away from the point that [`Interval`] regained control. /// /// This would look something like this: /// ```text @@ -280,20 +280,19 @@ pub enum MissedTickBehavior { /// ``` /// /// Note that as a result, the ticks are no longer guaranteed to happen at - /// a multiple of [`period`] from `delay`. + /// a multiple of `period` from `delay`. /// - /// [`period`]: Interval::period /// [`tick`]: Interval::tick Delay, - /// Skip the missed ticks and tick on the next multiple of [`period`]. + /// Skip the missed ticks and tick on the next multiple of `period`. /// /// When this strategy is used, after regaining control, [`Interval`] ticks /// immediately, then schedules the next tick on the closest multiple of - /// [`period`] from `delay`. Thus, the yielded value from + /// `period` from `delay`. Thus, the yielded value from /// [`tick`](Interval::tick) is an [`Instant`] that is some multiple of - /// [`period`] from `start`. However, that yielded [`Instant`] is not - /// guarenteed to be exactly one multiple of [`period`] from the tick that + /// `period` from `start`. However, that yielded [`Instant`] is not + /// guarenteed to be exactly one multiple of `period` from the tick that /// got blocked. /// /// This would look something like this: @@ -308,8 +307,6 @@ pub enum MissedTickBehavior { // Ready(s + 6p) // * Where `s` is the start time and `p` is the period /// ``` - /// - /// [`period`]: Interval::period Skip, } diff --git a/tokio/src/time/mod.rs b/tokio/src/time/mod.rs index b299cf70b75..0ce2fc0c797 100644 --- a/tokio/src/time/mod.rs +++ b/tokio/src/time/mod.rs @@ -52,12 +52,10 @@ //! # } //! ``` //! -//! A simple example using [`interval`](self::interval::interval) to execute -//! a task every two seconds. +//! A simple example using [`interval`] to execute a task every two seconds. //! -//! The difference between [`interval`](self::interval::interval) and -//! [`sleep`] is that an [`interval`](self::interval::interval) measures -//! the time since the last tick, which means that `.tick().await` may +//! The difference between [`interval`] and [`sleep`] is that an [`interval`] +//! 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 //! if some time has passed between calls to `.tick().await`. //! @@ -82,6 +80,8 @@ //! } //! } //! ``` +//! +//! [`interval`]: crate::time::interval() mod clock; pub(crate) use self::clock::Clock; From a3a8e0a22e2cd68db51d2321bc975e68bca14a1d Mon Sep 17 00:00:00 2001 From: Seth Brown Date: Wed, 5 May 2021 10:54:24 -0600 Subject: [PATCH 04/17] Get rid of interval_with_* functions --- tokio/src/time/interval.rs | 104 +------------------------------------ tokio/src/time/mod.rs | 5 +- 2 files changed, 3 insertions(+), 106 deletions(-) diff --git a/tokio/src/time/interval.rs b/tokio/src/time/interval.rs index 0c317085893..908cdd19500 100644 --- a/tokio/src/time/interval.rs +++ b/tokio/src/time/interval.rs @@ -82,9 +82,6 @@ pub fn interval(period: Duration) -> Interval { /// An interval will tick indefinitely. At any time, the [`Interval`] value can /// be dropped. This cancels the interval. /// -/// This function is equivalent to -/// [`interval_with_missed_tick_behavior_at(start, period, Default::default())`](interval_with_missed_tick_behavior_at) -/// /// # Panics /// /// This function panics if `period` is zero. @@ -109,105 +106,10 @@ pub fn interval(period: Duration) -> Interval { pub fn interval_at(start: Instant, period: Duration) -> Interval { assert!(period > Duration::new(0, 0), "`period` must be non-zero."); - interval_with_missed_tick_behavior_at(start, period, Default::default()) -} - -/// Creates new [`Interval`] with a specific [`MissedTickBehavior`] that yields -/// with interval of `period`. The first tick completes immediately. -/// -/// An interval will tick indefinitely. At any time, the [`Interval`] value can -/// be dropped. This cancels the interval. -/// -/// This function is equivalent to -/// [`interval_with_missed_tick_behavior_at(Instant::now(), period, missed_tick_behavior)`](interval_with_missed_tick_behavior_at) -/// -/// # Panics -/// -/// This function panics if `period` is zero. -/// -/// # Examples -/// -/// ``` -/// use tokio::time::{ -/// interval_with_missed_tick_behavior, -/// sleep, -/// Duration, -/// MissedTickBehavior, -/// }; -/// -/// #[tokio::main] -/// async fn main() { -/// let mut interval = interval_with_missed_tick_behavior( -/// Duration::from_millis(10), -/// MissedTickBehavior::Skip, -/// ); -/// -/// interval.tick().await; // ticks immediately -/// sleep(Duration::from_millis(25)).await; // simulating executor getting blocked -/// interval.tick().await; // ticks immediately, yielding an `Instant` 10ms after the starting tick -/// interval.tick().await; // ticks after 5ms, yielding an `Instant` 30ms after the starting tick -/// -/// // approximately 30ms have elapsed. -/// } -/// ``` -pub fn interval_with_missed_tick_behavior( - period: Duration, - missed_tick_behavior: MissedTickBehavior, -) -> Interval { - assert!(period > Duration::new(0, 0), "`period` must be non-zero."); - - interval_with_missed_tick_behavior_at(Instant::now(), period, missed_tick_behavior) -} - -/// Creates new [`Interval`] with a specific [`MissedTickBehavior`] that yields -/// with interval of `period`. The first tick completes at `start`. -/// -/// An interval will tick indefinitely. At any time, the [`Interval`] value can -/// be dropped. This cancels the interval. -/// -/// # Panics -/// -/// This function panics if `period` is zero. -/// -/// # Examples -/// -/// ``` -/// use tokio::time::{ -/// interval_with_missed_tick_behavior_at, -/// sleep, -/// Duration, -/// Instant, -/// MissedTickBehavior -/// }; -/// -/// #[tokio::main] -/// async fn main() { -/// let start = Instant::now() + Duration::from_millis(50); -/// let mut interval = interval_with_missed_tick_behavior_at( -/// start, -/// Duration::from_millis(10), -/// MissedTickBehavior::Skip, -/// ); -/// -/// interval.tick().await; // ticks after 50ms -/// sleep(Duration::from_millis(25)).await; // simulating executor getting blocked -/// interval.tick().await; // ticks immediately, yielding an `Instant` 10ms after the starting tick -/// interval.tick().await; // ticks after 5ms, yielding an `Instant` 30ms after the starting tick -/// -/// // approximately 30ms have elapsed. -/// } -/// ``` -pub fn interval_with_missed_tick_behavior_at( - start: Instant, - period: Duration, - missed_tick_behavior: MissedTickBehavior, -) -> Interval { - assert!(period > Duration::new(0, 0), "`period` must be non-zero."); - Interval { delay: Box::pin(sleep_until(start)), period, - missed_tick_behavior, + missed_tick_behavior: Default::default(), } } @@ -352,9 +254,7 @@ impl Default for MissedTickBehavior { } } -/// Interval returned by [`interval`], [`interval_at`], -/// [`interval_with_missed_tick_behavior`], and -/// [`interval_with_missed_tick_behavior_at`]. +/// Interval returned by [`interval`], [`interval_at`] /// /// This type allows you to wait on a sequence of instants with a certain /// duration between each instant. Unlike calling [`sleep`] in a loop, this lets diff --git a/tokio/src/time/mod.rs b/tokio/src/time/mod.rs index 0ce2fc0c797..281990ef9ac 100644 --- a/tokio/src/time/mod.rs +++ b/tokio/src/time/mod.rs @@ -99,10 +99,7 @@ mod instant; pub use self::instant::Instant; mod interval; -pub use interval::{ - interval, interval_at, interval_with_missed_tick_behavior, - interval_with_missed_tick_behavior_at, Interval, MissedTickBehavior, -}; +pub use interval::{interval, interval_at, Interval, MissedTickBehavior}; mod timeout; #[doc(inline)] From 578abf62c7363a3c585de17c35ecaf0eebb30941 Mon Sep 17 00:00:00 2001 From: Seth Brown Date: Wed, 5 May 2021 11:00:31 -0600 Subject: [PATCH 05/17] Adjust documentation for `MissedTickBehavior` --- tokio/src/time/interval.rs | 110 +++++++++++++++++++------------------ 1 file changed, 57 insertions(+), 53 deletions(-) diff --git a/tokio/src/time/interval.rs b/tokio/src/time/interval.rs index 908cdd19500..7f8cc776dd1 100644 --- a/tokio/src/time/interval.rs +++ b/tokio/src/time/interval.rs @@ -6,9 +6,9 @@ use std::task::{Context, Poll}; use std::{convert::TryInto, future::Future}; /// Creates new [`Interval`] that yields with interval of `period`. The first -/// tick completes immediately. The [`MissedTickBehavior`] is the -/// [default one](MissedTickBehavior::default), which is -/// [`Burst`](MissedTickBehavior::Burst). +/// tick completes immediately. The default [`MissedTickBehavior`] is +/// [`Burst`](MissedTickBehavior::Burst), but this can be configured +/// by calling [`set_missed_tick_behavior`](Interval::set_missed_tick_behavior). /// /// An interval will tick indefinitely. At any time, the [`Interval`] value can /// be dropped. This cancels the interval. @@ -39,7 +39,7 @@ use std::{convert::TryInto, future::Future}; /// /// A simple example using `interval` to execute a task every two seconds. /// -/// The difference between `interval` and [`sleep`] 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`] /// may wait for a shorter time than the duration specified for the interval /// if some time has passed between calls to [`.tick().await`]. @@ -75,9 +75,9 @@ pub fn interval(period: Duration) -> Interval { } /// Creates new [`Interval`] that yields with interval of `period` with the -/// first tick completing at `start`. The [`MissedTickBehavior`] is the -/// [default one](MissedTickBehavior::default), which is -/// [`Burst`](MissedTickBehavior::Burst). +/// first tick completing at `start`. The default [`MissedTickBehavior`] is +/// [`Burst`](MissedTickBehavior::Burst), but this can be configured +/// by calling [`set_missed_tick_behavior`](Interval::set_missed_tick_behavior). /// /// An interval will tick indefinitely. At any time, the [`Interval`] value can /// be dropped. This cancels the interval. @@ -115,27 +115,42 @@ pub fn interval_at(start: Instant, period: Duration) -> Interval { /// Defines the behavior of an [`Interval`] when it misses a tick. /// -/// Occasionally, the executor may be blocked, and as a result, [`Interval`] -/// misses a tick. By default, when this happens, [`Interval`] fires ticks -/// as quickly as it can until it is back to where it should be. However, -/// this is not always the desired behavior when ticks are missed. -/// `MissedTickBehavior` allows users to specify which behavior they want -/// [`Interval`] to exhibit. Each variant represents a different strategy. +/// Sometimes, an [`Interval`]'s tick is missed. For example, consider the +/// following: /// -/// Because the executor cannot guarantee exect precision with -/// timers, these strategies will only apply when the -/// error in time is greater than 5 milliseconds. +/// ```ignore +/// use tokio::time; +/// +/// let mut interval = time::interval(time::Duration::from_secs(2)); +/// for _ in 0..5 { +/// interval.tick().await; +/// // if this takes more than 2 seconds, a tick will be delayed +/// task_that_takes_one_to_three_seconds().await; +/// } +/// ``` +/// +/// Generally, a tick is missed if someone spends too much time without calling +/// [`tick()`](Interval::tick). +/// +/// By default, when at tick is missed, [`Interval`] fires ticks as quickly as +/// it can until it is back to where it should be. However, this is not always +/// the desired behavior. `MissedTickBehavior` allows users to specify which +/// behavior they want [`Interval`] to exhibit. Each variant represents a +/// different strategy. +/// +/// Note that because the executor cannot guarantee exect precision with timers, +/// these strategies will only apply when the error in time is greater than 5 +/// milliseconds. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum MissedTickBehavior { /// Tick as fast as possible until caught up. /// - /// When this strategy is used, after regaining control, [`Interval`] ticks - /// as fast as it can until it is caught up to where it should be had the - /// executor not been blocked. The [`Instant`]s yielded by - /// [`tick`](Interval::tick()) are the same as they would have been if the executor had not - /// been blocked. + /// When this strategy is used, [`Interval`] schedules ticks "normally" (the + /// same as it would have if the ticks hadn't been delayed), which results + /// in ticks being fired as fast as it can until it is caught up in time to + /// where it should be. /// - /// This would look something like this: + /// This looks something like this: /// ```text /// Expected ticks: | 1 | 2 | 3 | 4 | 5 | 6 | /// Actual ticks: | work -----| delay | work | work | work -| work -----| @@ -156,18 +171,13 @@ pub enum MissedTickBehavior { /// versions of Tokio. Burst, - /// Delay missed ticks to happen at multiples of `period` from when - /// [`Interval`] regained control. + /// Delay missed ticks to happen at multiples of `period` from when [`tick`] + /// was called. /// - /// When this strategy is used, after regaining control, [`Interval`] ticks - /// immediately, then schedules all future ticks to happen at a regular - /// `period` from the point when [`Interval`] regained control. - /// [`tick`] yields immediately with an [`Instant`] that represents the time - /// that the tick should have happened. All subsequent calls to - /// [`tick`] yield an [`Instant`] that is a multiple of - /// `period` away from the point that [`Interval`] regained control. + /// When this strategy is used, [`Interval`] schedules all future ticks to + /// happen at a regular `period` from the point when [`tick`] was called. /// - /// This would look something like this: + /// This looks something like this: /// ```text /// Expected ticks: | 1 | 2 | 3 | 4 | 5 | 6 | /// Actual ticks: | work -----| delay | work -----| work -----| work -----| @@ -189,15 +199,10 @@ pub enum MissedTickBehavior { /// Skip the missed ticks and tick on the next multiple of `period`. /// - /// When this strategy is used, after regaining control, [`Interval`] ticks - /// immediately, then schedules the next tick on the closest multiple of - /// `period` from `delay`. Thus, the yielded value from - /// [`tick`](Interval::tick) is an [`Instant`] that is some multiple of - /// `period` from `start`. However, that yielded [`Instant`] is not - /// guarenteed to be exactly one multiple of `period` from the tick that - /// got blocked. + /// When this strategy is used, [`Interval`] schedules the next tick for the + /// closest multiple of `period` from when the [`Interval`] first ticked. /// - /// This would look something like this: + /// This looks something like this: /// ```text /// Expected ticks: | 1 | 2 | 3 | 4 | 5 | 6 | /// Actual ticks: | work -----| delay | work ---| work -----| work -----| @@ -209,6 +214,9 @@ pub enum MissedTickBehavior { // Ready(s + 6p) // * Where `s` is the start time and `p` is the period /// ``` + /// + /// Note that the ticks aren't guarenteed to be one `period` away from the + /// last tick, but they will be a multiple of `period` away. Skip, } @@ -245,8 +253,8 @@ impl Default for MissedTickBehavior { /// For most usecases, the [`Burst`] strategy is what is desired. /// Additionally, to preserve backwards compatibility, the [`Burst`] /// strategy must be the default. For these reasons, - /// [`MissedTickBehavior::Burst`] is the default for - /// [`MissedTickBehavior`]. See [`Burst`] for more details. + /// [`MissedTickBehavior::Burst`] is the default for [`MissedTickBehavior`]. + /// See [`Burst`] for more details. /// /// [`Burst`]: MissedTickBehavior::Burst fn default() -> Self { @@ -254,7 +262,7 @@ impl Default for MissedTickBehavior { } } -/// Interval returned by [`interval`], [`interval_at`] +/// Interval returned by [`interval`] and [`interval_at`] /// /// This type allows you to wait on a sequence of instants with a certain /// duration between each instant. Unlike calling [`sleep`] in a loop, this lets @@ -272,8 +280,7 @@ pub struct Interval { /// The duration between values yielded by `Interval`. period: Duration, - /// The strategy `Interval` should use when the executor gets blocked and a - /// tick is missed. + /// The strategy `Interval` should use when a tick is missed. missed_tick_behavior: MissedTickBehavior, } @@ -323,10 +330,9 @@ impl Interval { let now = Instant::now(); - // If the executor was not blocked, and thus we are being called - // before the next tick is due, just schedule the next tick normally, - // one `period` after `scheduled_timeout`, when the last tick went - // off + // If a tick was not missed, and thus we are being called before the + // next tick is due, just schedule the next tick normally, one `period` + // after `timeout` // // However, if a tick took excessively long and we are now behind, // schedule the next tick according to how the user specified with @@ -344,8 +350,7 @@ impl Interval { Poll::Ready(timeout) } - /// Returns the [`MissedTickBehavior`] strategy that is currently being - /// used. + /// Returns the [`MissedTickBehavior`] strategy currently being used. pub fn missed_tick_behavior(&self) -> MissedTickBehavior { self.missed_tick_behavior } @@ -355,8 +360,7 @@ impl Interval { self.missed_tick_behavior = behavior; } - /// Resets the [`MissedTickBehavior`] strategy that should be used to the - /// [default one](MissedTickBehavior::default), which is + /// Resets the [`MissedTickBehavior`] strategy to the default, which is /// [`Burst`](MissedTickBehavior::Burst). pub fn reset_missed_tick_behavior(&mut self) { self.missed_tick_behavior = Default::default(); From c35509ddcf905e9bae4c42975265a5b09d8512f3 Mon Sep 17 00:00:00 2001 From: Seth Brown Date: Wed, 5 May 2021 11:17:39 -0600 Subject: [PATCH 06/17] Fix test to work with simplified API --- tokio/tests/time_interval.rs | 16 +++++----------- 1 file changed, 5 insertions(+), 11 deletions(-) diff --git a/tokio/tests/time_interval.rs b/tokio/tests/time_interval.rs index f7fbb5e76c6..5f7bf55f254 100644 --- a/tokio/tests/time_interval.rs +++ b/tokio/tests/time_interval.rs @@ -1,7 +1,7 @@ #![warn(rust_2018_idioms)] #![cfg(feature = "full")] -use tokio::time::{self, Duration, Instant}; +use tokio::time::{self, Duration, Instant, MissedTickBehavior}; use tokio_test::{assert_pending, assert_ready_eq, task}; use std::task::Poll; @@ -90,11 +90,8 @@ async fn delay() { // expect, so that the runtime will see that it is time to resolve the timer time::advance(ms(1)).await; - let mut i = task::spawn(time::interval_with_missed_tick_behavior_at( - start, - ms(300), - time::MissedTickBehavior::Delay, - )); + let mut i = task::spawn(time::interval_at(start, ms(300))); + i.set_missed_tick_behavior(MissedTickBehavior::Delay); check_interval_poll!(i, start, 0); @@ -145,11 +142,8 @@ async fn skip() { // expect, so that the runtime will see that it is time to resolve the timer time::advance(ms(1)).await; - let mut i = task::spawn(time::interval_with_missed_tick_behavior_at( - start, - ms(300), - time::MissedTickBehavior::Skip, - )); + let mut i = task::spawn(time::interval_at(start, ms(300))); + i.set_missed_tick_behavior(MissedTickBehavior::Skip); check_interval_poll!(i, start, 0); From 93bdd33cefec474a9a955db85ce2382e467f5ac7 Mon Sep 17 00:00:00 2001 From: Seth Brown Date: Wed, 5 May 2021 11:39:42 -0600 Subject: [PATCH 07/17] Remove `reset_missed_tick_behavior` --- tokio/src/time/interval.rs | 6 ------ 1 file changed, 6 deletions(-) diff --git a/tokio/src/time/interval.rs b/tokio/src/time/interval.rs index 7f8cc776dd1..8c589ea91b4 100644 --- a/tokio/src/time/interval.rs +++ b/tokio/src/time/interval.rs @@ -360,12 +360,6 @@ impl Interval { self.missed_tick_behavior = behavior; } - /// Resets the [`MissedTickBehavior`] strategy to the default, which is - /// [`Burst`](MissedTickBehavior::Burst). - pub fn reset_missed_tick_behavior(&mut self) { - self.missed_tick_behavior = Default::default(); - } - /// Returns the period of the interval. pub fn period(&self) -> Duration { self.period From 049eaffcc9c061c61e7122392b423cd0d6f882f5 Mon Sep 17 00:00:00 2001 From: sb64 <53383020+sb64@users.noreply.github.com> Date: Fri, 14 May 2021 14:48:44 -0600 Subject: [PATCH 08/17] Remove unnecessary documentation Co-authored-by: Alice Ryhl --- tokio/src/time/interval.rs | 3 --- 1 file changed, 3 deletions(-) diff --git a/tokio/src/time/interval.rs b/tokio/src/time/interval.rs index 8c589ea91b4..790bc31e63c 100644 --- a/tokio/src/time/interval.rs +++ b/tokio/src/time/interval.rs @@ -166,9 +166,6 @@ pub enum MissedTickBehavior { /// /// This is the default behavior when [`Interval`] is created with /// [`interval`] and [`interval_at`]. - /// - /// Note: this is the behavior that [`Interval`] exhibited in previous - /// versions of Tokio. Burst, /// Delay missed ticks to happen at multiples of `period` from when [`tick`] From 8abdbadefd2dd6feb6361661bd6a473ae23be503 Mon Sep 17 00:00:00 2001 From: sb64 <53383020+sb64@users.noreply.github.com> Date: Fri, 14 May 2021 14:48:56 -0600 Subject: [PATCH 09/17] Fix typo Co-authored-by: Alice Ryhl --- tokio/src/time/interval.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tokio/src/time/interval.rs b/tokio/src/time/interval.rs index 790bc31e63c..33cd0edad5a 100644 --- a/tokio/src/time/interval.rs +++ b/tokio/src/time/interval.rs @@ -138,7 +138,7 @@ pub fn interval_at(start: Instant, period: Duration) -> Interval { /// behavior they want [`Interval`] to exhibit. Each variant represents a /// different strategy. /// -/// Note that because the executor cannot guarantee exect precision with timers, +/// Note that because the executor cannot guarantee exact precision with timers, /// these strategies will only apply when the error in time is greater than 5 /// milliseconds. #[derive(Debug, Clone, Copy, PartialEq, Eq)] From 3df685f294d0eeefafc3052fa24831074250c2e3 Mon Sep 17 00:00:00 2001 From: sb64 <53383020+sb64@users.noreply.github.com> Date: Fri, 14 May 2021 14:51:20 -0600 Subject: [PATCH 10/17] Docs: remove `ignore` label --- tokio/src/time/interval.rs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/tokio/src/time/interval.rs b/tokio/src/time/interval.rs index 33cd0edad5a..808a0e8a317 100644 --- a/tokio/src/time/interval.rs +++ b/tokio/src/time/interval.rs @@ -118,9 +118,11 @@ pub fn interval_at(start: Instant, period: Duration) -> Interval { /// Sometimes, an [`Interval`]'s tick is missed. For example, consider the /// following: /// -/// ```ignore +/// ``` /// use tokio::time; /// +/// # async fn task_that_takes_one_to_three_seconds() {} +/// /// let mut interval = time::interval(time::Duration::from_secs(2)); /// for _ in 0..5 { /// interval.tick().await; From 6333e6ef6f738039a5bb49bf2da2413cb83f48ab Mon Sep 17 00:00:00 2001 From: sb64 <53383020+sb64@users.noreply.github.com> Date: Fri, 14 May 2021 15:02:06 -0600 Subject: [PATCH 11/17] Fix documentation error --- tokio/src/time/interval.rs | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/tokio/src/time/interval.rs b/tokio/src/time/interval.rs index 808a0e8a317..6642a9767dd 100644 --- a/tokio/src/time/interval.rs +++ b/tokio/src/time/interval.rs @@ -123,11 +123,14 @@ pub fn interval_at(start: Instant, period: Duration) -> Interval { /// /// # async fn task_that_takes_one_to_three_seconds() {} /// -/// let mut interval = time::interval(time::Duration::from_secs(2)); -/// for _ in 0..5 { -/// interval.tick().await; -/// // if this takes more than 2 seconds, a tick will be delayed -/// task_that_takes_one_to_three_seconds().await; +/// #[tokio::main] +/// async fn main() { +/// let mut interval = time::interval(time::Duration::from_secs(2)); +/// for _ in 0..5 { +/// interval.tick().await; +/// // if this takes more than 2 seconds, a tick will be delayed +/// task_that_takes_one_to_three_seconds().await; +/// } /// } /// ``` /// From 8a2d0419f76618bc15098b04f8fbd285eb656ef8 Mon Sep 17 00:00:00 2001 From: sb64 <53383020+sb64@users.noreply.github.com> Date: Fri, 14 May 2021 15:03:43 -0600 Subject: [PATCH 12/17] Simplify diagram? --- tokio/src/time/interval.rs | 22 ---------------------- 1 file changed, 22 deletions(-) diff --git a/tokio/src/time/interval.rs b/tokio/src/time/interval.rs index 6642a9767dd..3f87da5dc19 100644 --- a/tokio/src/time/interval.rs +++ b/tokio/src/time/interval.rs @@ -159,14 +159,6 @@ pub enum MissedTickBehavior { /// ```text /// Expected ticks: | 1 | 2 | 3 | 4 | 5 | 6 | /// Actual ticks: | work -----| delay | work | work | work -| work -----| - // Poll behavior: | | | | | | | | - // | | | | | | | | - // Ready(s) | | Ready(s + 2p) | | | | - // Pending | Ready(s + 3p) | | | - // Ready(s + p) Ready(s + 4p) | | - // Ready(s + 5p) | - // Ready(s + 6p) - // * Where `s` is the start time and `p` is the period /// ``` /// /// This is the default behavior when [`Interval`] is created with @@ -183,14 +175,6 @@ pub enum MissedTickBehavior { /// ```text /// Expected ticks: | 1 | 2 | 3 | 4 | 5 | 6 | /// Actual ticks: | work -----| delay | work -----| work -----| work -----| - // Poll behavior: | | | | | | | | - // | | | | | | | | - // Ready(s) | | Ready(s + 2p) | | | | - // Pending | Pending | | | - // Ready(s + p) Ready(s + 2p + d) | | - // Ready(s + 3p + d) | - // Ready(s + 4p + d) - // * Where `s` is the start time, `p` is the period, and `d` is the delay /// ``` /// /// Note that as a result, the ticks are no longer guaranteed to happen at @@ -208,12 +192,6 @@ pub enum MissedTickBehavior { /// ```text /// Expected ticks: | 1 | 2 | 3 | 4 | 5 | 6 | /// Actual ticks: | work -----| delay | work ---| work -----| work -----| - // Poll behavior: | | | | | | | - // | | | | | | | - // Ready(s) | | Ready(s + 2p) | | | - // Pending | Ready(s + 4p) | | - // Ready(s + p) Ready(s + 5p) | - // Ready(s + 6p) // * Where `s` is the start time and `p` is the period /// ``` /// From be0760f0ce2a737c91de90ea69b11b4652f10f17 Mon Sep 17 00:00:00 2001 From: Seth Brown Date: Fri, 14 May 2021 15:44:26 -0600 Subject: [PATCH 13/17] Forgot to remove one comment --- tokio/src/time/interval.rs | 1 - 1 file changed, 1 deletion(-) diff --git a/tokio/src/time/interval.rs b/tokio/src/time/interval.rs index 3f87da5dc19..c4ab8abc0e3 100644 --- a/tokio/src/time/interval.rs +++ b/tokio/src/time/interval.rs @@ -192,7 +192,6 @@ pub enum MissedTickBehavior { /// ```text /// Expected ticks: | 1 | 2 | 3 | 4 | 5 | 6 | /// Actual ticks: | work -----| delay | work ---| work -----| work -----| - // * Where `s` is the start time and `p` is the period /// ``` /// /// Note that the ticks aren't guarenteed to be one `period` away from the From 3a97d62740bacd43bedae87b1a2bcdb50fa5b8c4 Mon Sep 17 00:00:00 2001 From: Seth Brown Date: Wed, 26 May 2021 16:47:18 -0700 Subject: [PATCH 14/17] Documentation overhaul, doctests not passing yet --- tokio/src/time/interval.rs | 265 +++++++++++++++++++++++++++++++++---- 1 file changed, 240 insertions(+), 25 deletions(-) diff --git a/tokio/src/time/interval.rs b/tokio/src/time/interval.rs index c4ab8abc0e3..497f8886c68 100644 --- a/tokio/src/time/interval.rs +++ b/tokio/src/time/interval.rs @@ -119,13 +119,13 @@ pub fn interval_at(start: Instant, period: Duration) -> Interval { /// following: /// /// ``` -/// use tokio::time; -/// +/// use tokio::time::{self, Duration}; /// # async fn task_that_takes_one_to_three_seconds() {} /// /// #[tokio::main] /// async fn main() { -/// let mut interval = time::interval(time::Duration::from_secs(2)); +/// // ticks every 2 seconds +/// let mut interval = time::interval(Duration::from_secs(2)); /// for _ in 0..5 { /// interval.tick().await; /// // if this takes more than 2 seconds, a tick will be delayed @@ -134,17 +134,16 @@ pub fn interval_at(start: Instant, period: Duration) -> Interval { /// } /// ``` /// -/// Generally, a tick is missed if someone spends too much time without calling -/// [`tick()`](Interval::tick). +/// Generally, a tick is missed if too much time is spent without calling +/// [`Interval::tick()`]. /// -/// By default, when at tick is missed, [`Interval`] fires ticks as quickly as -/// it can until it is back to where it should be. However, this is not always -/// the desired behavior. `MissedTickBehavior` allows users to specify which -/// behavior they want [`Interval`] to exhibit. Each variant represents a -/// different strategy. +/// By default, when a tick is missed, [`Interval`] fires ticks as quickly as it +/// can until it is "caught up" in time to where it should be. +/// `MissedTickBehavior` can be used to specify a different behavior for +/// [`Interval`] to exhibit. Each variant represents a different strategy. /// /// Note that because the executor cannot guarantee exact precision with timers, -/// these strategies will only apply when the error in time is greater than 5 +/// these strategies will only apply when the delay is greater than 5 /// milliseconds. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum MissedTickBehavior { @@ -152,8 +151,12 @@ pub enum MissedTickBehavior { /// /// When this strategy is used, [`Interval`] schedules ticks "normally" (the /// same as it would have if the ticks hadn't been delayed), which results - /// in ticks being fired as fast as it can until it is caught up in time to - /// where it should be. + /// in it firing ticks as fast as possible until it is caught up in time to + /// where it should be. Unlike [`Delay`] and [`Skip`], the ticks yielded + /// when `Burst` is used (the [`Instant`]s that [`tick`](Interval::tick) + /// yields) aren't different than they would have been if a tick had not + /// been missed. Like [`Skip`], and unlike [`Delay`], the ticks may be + /// shortened. /// /// This looks something like this: /// ```text @@ -161,15 +164,91 @@ pub enum MissedTickBehavior { /// Actual ticks: | work -----| delay | work | work | work -| work -----| /// ``` /// + /// In code: + /// + /// ``` + /// use tokio::time::{self, Duration, Instant}; + /// # async fn task_that_takes_five_seconds() { + /// # time::sleep(Duration::from_secs(5)).await + /// # } + /// + /// #[tokio::main] + /// async fn main() { + /// // ticks every two seconds + /// let mut interval = time::interval(Duration::from_secs(2)); + /// + /// let start = Instant::now(); + /// + /// // ticks immediately, as expected + /// // `deadline` is when `interval` was scheduled to tick; when + /// // `interval` is not delayed, `deadline` should be the same as, or + /// // really close to, the time right now + /// let deadline = interval.tick().await; + /// // because tokio's timer can't guarentee precision beyond one + /// // millisecond, we test whether deadline is within one millisecond + /// // of where we expect it to be + /// assert!( + /// start - Duration::from_millis(1) <= deadline + /// && deadline <= start + Duration::from_millis(1) + /// ); + /// + /// // ticks normally, after two seconds + /// let deadline = interval.tick().await; + /// assert!( + /// start + Duration::from_secs(2) - Duration::from_millis(1) <= deadline + /// && deadline <= start + Duration::from_secs(2) + Duration::from_millis(1) + /// ); + /// + /// task_that_takes_five_seconds().await; + /// // `interval` is now behind; we are at seven seconds past `start`, + /// // but `interval` is scheduled to tick at four seconds past `start` + /// + /// // ticks immediately, as it was supposed to go off three seconds ago + /// let deadline = interval.tick().await; + /// assert!( + /// start + Duration::from_secs(4) - Duration::from_millis(1) <= deadline + /// && deadline <= start + Duration::from_secs(4) + Duration::from_millis(1) + /// ); + /// + /// // ticks immediately, as it was supposed to go off one second ago + /// let deadline = interval.tick().await; + /// assert!( + /// start + Duration::from_secs(6) - Duration::from_millis(1) <= deadline + /// && deadline <= start + Duration::from_secs(6) + Duration::from_millis(1) + /// ); + /// + /// // ticks after one second + /// let deadline = interval.tick().await; + /// assert!( + /// start + Duration::from_secs(8) - Duration::from_millis(1) <= deadline + /// && deadline <= start + Duration::from_secs(8) + Duration::from_millis(1) + /// ); + /// + /// // ticks normally, after two seconds + /// let deadline = interval.tick().await; + /// assert!( + /// start + Duration::from_secs(10) - Duration::from_millis(1) <= deadline + /// && deadline <= start + Duration::from_secs(10) + Duration::from_millis(1) + /// ); + /// } + /// ``` + /// /// This is the default behavior when [`Interval`] is created with /// [`interval`] and [`interval_at`]. + /// + /// [`Delay`]: MissedTickBehavior::Delay + /// [`Skip`]: MissedTickBehavior::Skip Burst, - /// Delay missed ticks to happen at multiples of `period` from when [`tick`] - /// was called. + /// Tick at multiples of `period` from when [`tick`] was called, rather than + /// from `start`. /// - /// When this strategy is used, [`Interval`] schedules all future ticks to + /// When this strategy is used and [`Interval`] has missed a tick, instead + /// of scheduling ticks to fire at multiples of `period` from `start` (the + /// time when the first tick was fired), it schedules all future ticks to /// happen at a regular `period` from the point when [`tick`] was called. + /// Unlike [`Burst`] and [`Skip`], ticks are not shortened, and they aren't + /// guaranteed to happen at a multiple of `period` from `start` any longer. /// /// This looks something like this: /// ```text @@ -177,16 +256,87 @@ pub enum MissedTickBehavior { /// Actual ticks: | work -----| delay | work -----| work -----| work -----| /// ``` /// - /// Note that as a result, the ticks are no longer guaranteed to happen at - /// a multiple of `period` from `delay`. + /// In code: + /// + /// ``` + /// use tokio::time::{self, Duration, Instant, MissedTickBehavior}; + /// # async fn task_that_takes_five_seconds() { + /// # time::sleep(Duration::from_secs(5)).await + /// # } + /// + /// #[tokio::main] + /// async fn main() { + /// // ticks every two seconds + /// let mut interval = time::interval(Duration::from_secs(2)); + /// interval.set_missed_tick_behavior(MissedTickBehavior::Delay); + /// + /// let start = Instant::now(); + /// + /// // ticks immediately, as expected + /// // `deadline` is when `interval` was scheduled to tick; when + /// // `interval` is not delayed, `deadline` should be the same as, or + /// // really close to, the time right now + /// let deadline = interval.tick().await; + /// // because tokio's timer can't guarentee precision beyond one + /// // millisecond, we test whether deadline is within one millisecond + /// // of where we expect it to be + /// assert!( + /// start - Duration::from_millis(1) <= deadline + /// && deadline <= start + Duration::from_millis(1) + /// ); + /// + /// // ticks normally, after two seconds + /// let deadline = interval.tick().await; + /// assert!( + /// start + Duration::from_secs(2) - Duration::from_millis(1) <= deadline + /// && deadline <= start + Duration::from_secs(2) + Duration::from_millis(1) + /// ); + /// + /// // `interval` is now behind; we are at seven seconds past `start`, + /// // but `interval` is scheduled to tick at four seconds past `start` + /// task_that_takes_five_seconds().await; /// + /// // ticks immediately, as it was supposed to go off three seconds ago + /// let deadline = interval.tick().await; + /// assert!( + /// start + Duration::from_secs(4) - Duration::from_millis(1) <= deadline + /// && deadline <= start + Duration::from_secs(4) + Duration::from_millis(1) + /// ); + /// + /// // ticks normally after two seconds, one `period` after when we last + /// // called `tick` (rather than one `period` after the last `deadline`) + /// let deadline = interval.tick().await; + /// assert!( + /// start + Duration::from_secs(9) - Duration::from_millis(1) <= deadline + /// && deadline <= start + Duration::from_secs(9) + Duration::from_millis(1) + /// ); + /// + /// // ticks normally, after two seconds + /// let deadline = interval.tick().await; + /// assert!( + /// start + Duration::from_secs(11) - Duration::from_millis(1) <= deadline + /// && deadline <= start + Duration::from_secs(11) + Duration::from_millis(1) + /// ); + /// } + /// ``` + /// + /// [`Burst`]: MissedTickBehavior::Burst + /// [`Skip`]: MissedTickBehavior::Skip /// [`tick`]: Interval::tick Delay, - /// Skip the missed ticks and tick on the next multiple of `period`. + /// Skip missed ticks and tick on the next multiple of `period` from + /// `start`. /// - /// When this strategy is used, [`Interval`] schedules the next tick for the - /// closest multiple of `period` from when the [`Interval`] first ticked. + /// When this strategy is used, [`Interval`] schedules the next tick to fire + /// at the next-closest tick that is a multiple of `period` away from + /// `start` (the point where [`Interval`] first ticked). Like [`Burst`], all + /// ticks remain multiples of `period` away from `start`, but unlike + /// [`Burst`], the ticks may not be *one* multiple of `period` away from the + /// last tick. Like [`Delay`], the ticks are no longer the same as they + /// would have been if ticks had not been missed, but unlike [`Delay`], and + /// like [`Burst`], the ticks may be shortened to be less than one `period` + /// away from each other. /// /// This looks something like this: /// ```text @@ -194,8 +344,73 @@ pub enum MissedTickBehavior { /// Actual ticks: | work -----| delay | work ---| work -----| work -----| /// ``` /// - /// Note that the ticks aren't guarenteed to be one `period` away from the - /// last tick, but they will be a multiple of `period` away. + /// In code: + /// + /// ``` + /// use tokio::time::{self, Duration, Instant, MissedTickBehavior}; + /// # async fn task_that_takes_five_seconds() { + /// # time::sleep(Duration::from_secs(5)).await + /// # } + /// + /// #[tokio::main] + /// async fn main() { + /// // ticks every two seconds + /// let mut interval = time::interval(Duration::from_secs(2)); + /// interval.set_missed_tick_behavior(MissedTickBehavior::Skip); + /// + /// let start = Instant::now(); + /// + /// // ticks immediately, as expected + /// // `deadline` is when `interval` was scheduled to tick; when + /// // `interval` is not delayed, `deadline` should be the same as, or + /// // really close to, the time right now + /// let deadline = interval.tick().await; + /// // because tokio's timer can't guarentee precision beyond one + /// // millisecond, we test whether deadline is within one millisecond + /// // of where we expect it to be + /// assert!( + /// start - Duration::from_millis(1) <= deadline + /// && deadline <= start + Duration::from_millis(1) + /// ); + /// + /// // ticks normally, after two seconds + /// let deadline = interval.tick().await; + /// assert!( + /// start + Duration::from_secs(2) - Duration::from_millis(1) <= deadline + /// && deadline <= start + Duration::from_secs(2) + Duration::from_millis(1) + /// ); + /// + /// // `interval` is now behind; we are at seven seconds past `start`, + /// // but `interval` is scheduled to tick at four seconds past `start` + /// task_that_takes_five_seconds().await; + /// + /// // ticks after one second, because the next-closest multiple of + /// // `period` from `start` is at eight seconds after `start` + /// let deadline = interval.tick().await; + /// assert!( + /// start + Duration::from_secs(8) - Duration::from_millis(1) <= deadline + /// && deadline <= start + Duration::from_secs(8) + Duration::from_millis(1) + /// ); + /// + /// // ticks normally after two seconds, one `period` after when we last + /// // called `tick` (which is also five periods after `start`) + /// let deadline = interval.tick().await; + /// assert!( + /// start + Duration::from_secs(10) - Duration::from_millis(1) <= deadline + /// && deadline <= start + Duration::from_secs(10) + Duration::from_millis(1) + /// ); + /// + /// // ticks normally, after two seconds + /// let deadline = interval.tick().await; + /// assert!( + /// start + Duration::from_secs(12) - Duration::from_millis(1) <= deadline + /// && deadline <= start + Duration::from_secs(12) + Duration::from_millis(1) + /// ); + /// } + /// ``` + /// + /// [`Burst`]: MissedTickBehavior::Burst + /// [`Delay`]: MissedTickBehavior::Delay Skip, } @@ -304,7 +519,7 @@ impl Interval { // Wait for the delay to be done ready!(Pin::new(&mut self.delay).poll(cx)); - // Get the time at which the `delay` was supposed to complete + // Get the time when we were scheduled to tick let timeout = self.delay.deadline(); let now = Instant::now(); @@ -325,7 +540,7 @@ impl Interval { self.delay.as_mut().reset(next); - // Return the current instant + // Return the time when we were scheduled to tick Poll::Ready(timeout) } From b920b20b2103845dc609d01427b7770f486e75d5 Mon Sep 17 00:00:00 2001 From: Seth Brown Date: Wed, 26 May 2021 17:20:44 -0700 Subject: [PATCH 15/17] Simplify doctests and finalize documentation --- tokio/src/time/interval.rs | 242 ++++++++++--------------------------- 1 file changed, 62 insertions(+), 180 deletions(-) diff --git a/tokio/src/time/interval.rs b/tokio/src/time/interval.rs index 497f8886c68..61159a6a163 100644 --- a/tokio/src/time/interval.rs +++ b/tokio/src/time/interval.rs @@ -167,70 +167,27 @@ pub enum MissedTickBehavior { /// In code: /// /// ``` - /// use tokio::time::{self, Duration, Instant}; - /// # async fn task_that_takes_five_seconds() { - /// # time::sleep(Duration::from_secs(5)).await + /// use tokio::time::{interval, Duration}; + /// # async fn task_that_takes_more_than_50_millis() {} + /// + /// # #[tokio::main(flavor = "current_thread")] + /// # async fn main() { + /// let mut interval = interval(Duration::from_millis(50)); + /// + /// task_that_takes_more_than_50_millis().await; + /// // The `Interval` has missed a tick + /// + /// // Since we have exceeded our timeout, this will resolve immediately + /// interval.tick().await; + /// + /// // If we missed our tick by more than 50ms (if we are over 100ms after + /// // `start`), this will also resolve immediately, otherwise, it will + /// // resolve 100ms after `start`. That is, in `tick`, even though we + /// // recognize that we missed a tick, we schedule the next tick to happen + /// // 50ms (or whatever the `period` is) from when were were *supposed* to + /// // tick + /// interval.tick().await; /// # } - /// - /// #[tokio::main] - /// async fn main() { - /// // ticks every two seconds - /// let mut interval = time::interval(Duration::from_secs(2)); - /// - /// let start = Instant::now(); - /// - /// // ticks immediately, as expected - /// // `deadline` is when `interval` was scheduled to tick; when - /// // `interval` is not delayed, `deadline` should be the same as, or - /// // really close to, the time right now - /// let deadline = interval.tick().await; - /// // because tokio's timer can't guarentee precision beyond one - /// // millisecond, we test whether deadline is within one millisecond - /// // of where we expect it to be - /// assert!( - /// start - Duration::from_millis(1) <= deadline - /// && deadline <= start + Duration::from_millis(1) - /// ); - /// - /// // ticks normally, after two seconds - /// let deadline = interval.tick().await; - /// assert!( - /// start + Duration::from_secs(2) - Duration::from_millis(1) <= deadline - /// && deadline <= start + Duration::from_secs(2) + Duration::from_millis(1) - /// ); - /// - /// task_that_takes_five_seconds().await; - /// // `interval` is now behind; we are at seven seconds past `start`, - /// // but `interval` is scheduled to tick at four seconds past `start` - /// - /// // ticks immediately, as it was supposed to go off three seconds ago - /// let deadline = interval.tick().await; - /// assert!( - /// start + Duration::from_secs(4) - Duration::from_millis(1) <= deadline - /// && deadline <= start + Duration::from_secs(4) + Duration::from_millis(1) - /// ); - /// - /// // ticks immediately, as it was supposed to go off one second ago - /// let deadline = interval.tick().await; - /// assert!( - /// start + Duration::from_secs(6) - Duration::from_millis(1) <= deadline - /// && deadline <= start + Duration::from_secs(6) + Duration::from_millis(1) - /// ); - /// - /// // ticks after one second - /// let deadline = interval.tick().await; - /// assert!( - /// start + Duration::from_secs(8) - Duration::from_millis(1) <= deadline - /// && deadline <= start + Duration::from_secs(8) + Duration::from_millis(1) - /// ); - /// - /// // ticks normally, after two seconds - /// let deadline = interval.tick().await; - /// assert!( - /// start + Duration::from_secs(10) - Duration::from_millis(1) <= deadline - /// && deadline <= start + Duration::from_secs(10) + Duration::from_millis(1) - /// ); - /// } /// ``` /// /// This is the default behavior when [`Interval`] is created with @@ -259,65 +216,28 @@ pub enum MissedTickBehavior { /// In code: /// /// ``` - /// use tokio::time::{self, Duration, Instant, MissedTickBehavior}; - /// # async fn task_that_takes_five_seconds() { - /// # time::sleep(Duration::from_secs(5)).await + /// use tokio::time::{interval, Duration, MissedTickBehavior}; + /// # async fn task_that_takes_more_than_50_millis() {} + /// + /// # #[tokio::main(flavor = "current_thread")] + /// # async fn main() { + /// let mut interval = interval(Duration::from_millis(50)); + /// interval.set_missed_tick_behavior(MissedTickBehavior::Delay); + /// + /// task_that_takes_more_than_50_millis().await; + /// // The `Interval` has missed a tick + /// + /// // Since we have exceeded our timeout, this will resolve immediately + /// interval.tick().await; + /// + /// // But this one, rather than also resolving immediately, as might happen + /// // with the `Burst` or `Skip` behaviors, will not resolve until + /// // 50ms after the call to `tick` up above. That is, in `tick`, when we + /// // recognize that we missed a tick, we schedule the next tick to happen + /// // 50ms (or whatever the `period` is) from right then, not from when + /// // were were *supposed* to tick + /// interval.tick().await; /// # } - /// - /// #[tokio::main] - /// async fn main() { - /// // ticks every two seconds - /// let mut interval = time::interval(Duration::from_secs(2)); - /// interval.set_missed_tick_behavior(MissedTickBehavior::Delay); - /// - /// let start = Instant::now(); - /// - /// // ticks immediately, as expected - /// // `deadline` is when `interval` was scheduled to tick; when - /// // `interval` is not delayed, `deadline` should be the same as, or - /// // really close to, the time right now - /// let deadline = interval.tick().await; - /// // because tokio's timer can't guarentee precision beyond one - /// // millisecond, we test whether deadline is within one millisecond - /// // of where we expect it to be - /// assert!( - /// start - Duration::from_millis(1) <= deadline - /// && deadline <= start + Duration::from_millis(1) - /// ); - /// - /// // ticks normally, after two seconds - /// let deadline = interval.tick().await; - /// assert!( - /// start + Duration::from_secs(2) - Duration::from_millis(1) <= deadline - /// && deadline <= start + Duration::from_secs(2) + Duration::from_millis(1) - /// ); - /// - /// // `interval` is now behind; we are at seven seconds past `start`, - /// // but `interval` is scheduled to tick at four seconds past `start` - /// task_that_takes_five_seconds().await; - /// - /// // ticks immediately, as it was supposed to go off three seconds ago - /// let deadline = interval.tick().await; - /// assert!( - /// start + Duration::from_secs(4) - Duration::from_millis(1) <= deadline - /// && deadline <= start + Duration::from_secs(4) + Duration::from_millis(1) - /// ); - /// - /// // ticks normally after two seconds, one `period` after when we last - /// // called `tick` (rather than one `period` after the last `deadline`) - /// let deadline = interval.tick().await; - /// assert!( - /// start + Duration::from_secs(9) - Duration::from_millis(1) <= deadline - /// && deadline <= start + Duration::from_secs(9) + Duration::from_millis(1) - /// ); - /// - /// // ticks normally, after two seconds - /// let deadline = interval.tick().await; - /// assert!( - /// start + Duration::from_secs(11) - Duration::from_millis(1) <= deadline - /// && deadline <= start + Duration::from_secs(11) + Duration::from_millis(1) - /// ); - /// } /// ``` /// /// [`Burst`]: MissedTickBehavior::Burst @@ -347,66 +267,28 @@ pub enum MissedTickBehavior { /// In code: /// /// ``` - /// use tokio::time::{self, Duration, Instant, MissedTickBehavior}; - /// # async fn task_that_takes_five_seconds() { - /// # time::sleep(Duration::from_secs(5)).await + /// use tokio::time::{interval, Duration, MissedTickBehavior}; + /// # async fn task_that_takes_more_than_50_millis() {} + /// + /// # #[tokio::main(flavor = "current_thread")] + /// # async fn main() { + /// let mut interval = interval(Duration::from_millis(50)); + /// interval.set_missed_tick_behavior(MissedTickBehavior::Skip); + /// + /// task_that_takes_more_than_50_millis().await; + /// // The `Interval` has missed a tick + /// + /// // Since we have exceeded our timeout, this will resolve immediately + /// interval.tick().await; + /// + /// // This one will resolve at the closest multiple of `period` from + /// // `start` after the call to `tick` up above. That is, in `tick`, when + /// // we recognize that we missed a tick, we schedule the next tick to + /// // happen at the next `period` from `start` that is after right now, + /// // rather than scheduling it to happen one `period` from when were were + /// // *supposed* to tick, or one period after right now. + /// interval.tick().await; /// # } - /// - /// #[tokio::main] - /// async fn main() { - /// // ticks every two seconds - /// let mut interval = time::interval(Duration::from_secs(2)); - /// interval.set_missed_tick_behavior(MissedTickBehavior::Skip); - /// - /// let start = Instant::now(); - /// - /// // ticks immediately, as expected - /// // `deadline` is when `interval` was scheduled to tick; when - /// // `interval` is not delayed, `deadline` should be the same as, or - /// // really close to, the time right now - /// let deadline = interval.tick().await; - /// // because tokio's timer can't guarentee precision beyond one - /// // millisecond, we test whether deadline is within one millisecond - /// // of where we expect it to be - /// assert!( - /// start - Duration::from_millis(1) <= deadline - /// && deadline <= start + Duration::from_millis(1) - /// ); - /// - /// // ticks normally, after two seconds - /// let deadline = interval.tick().await; - /// assert!( - /// start + Duration::from_secs(2) - Duration::from_millis(1) <= deadline - /// && deadline <= start + Duration::from_secs(2) + Duration::from_millis(1) - /// ); - /// - /// // `interval` is now behind; we are at seven seconds past `start`, - /// // but `interval` is scheduled to tick at four seconds past `start` - /// task_that_takes_five_seconds().await; - /// - /// // ticks after one second, because the next-closest multiple of - /// // `period` from `start` is at eight seconds after `start` - /// let deadline = interval.tick().await; - /// assert!( - /// start + Duration::from_secs(8) - Duration::from_millis(1) <= deadline - /// && deadline <= start + Duration::from_secs(8) + Duration::from_millis(1) - /// ); - /// - /// // ticks normally after two seconds, one `period` after when we last - /// // called `tick` (which is also five periods after `start`) - /// let deadline = interval.tick().await; - /// assert!( - /// start + Duration::from_secs(10) - Duration::from_millis(1) <= deadline - /// && deadline <= start + Duration::from_secs(10) + Duration::from_millis(1) - /// ); - /// - /// // ticks normally, after two seconds - /// let deadline = interval.tick().await; - /// assert!( - /// start + Duration::from_secs(12) - Duration::from_millis(1) <= deadline - /// && deadline <= start + Duration::from_secs(12) + Duration::from_millis(1) - /// ); - /// } /// ``` /// /// [`Burst`]: MissedTickBehavior::Burst From 0b7adb18aa34eb03564e1230ab17fde15786fed3 Mon Sep 17 00:00:00 2001 From: Seth Brown Date: Wed, 26 May 2021 19:50:20 -0700 Subject: [PATCH 16/17] Rework doctests to emphasize each one's unique features --- tokio/src/time/interval.rs | 44 +++++++++++++++++++++----------------- 1 file changed, 24 insertions(+), 20 deletions(-) diff --git a/tokio/src/time/interval.rs b/tokio/src/time/interval.rs index 61159a6a163..09f8bc07369 100644 --- a/tokio/src/time/interval.rs +++ b/tokio/src/time/interval.rs @@ -120,16 +120,16 @@ pub fn interval_at(start: Instant, period: Duration) -> Interval { /// /// ``` /// use tokio::time::{self, Duration}; -/// # async fn task_that_takes_one_to_three_seconds() {} +/// # async fn task_that_takes_one_to_three_millis() {} /// /// #[tokio::main] /// async fn main() { /// // ticks every 2 seconds -/// let mut interval = time::interval(Duration::from_secs(2)); +/// let mut interval = time::interval(Duration::from_millis(2)); /// for _ in 0..5 { /// interval.tick().await; -/// // if this takes more than 2 seconds, a tick will be delayed -/// task_that_takes_one_to_three_seconds().await; +/// // if this takes more than 2 milliseconds, a tick will be delayed +/// task_that_takes_one_to_three_millis().await; /// } /// } /// ``` @@ -168,24 +168,31 @@ pub enum MissedTickBehavior { /// /// ``` /// use tokio::time::{interval, Duration}; - /// # async fn task_that_takes_more_than_50_millis() {} + /// # async fn task_that_takes_200_millis() {} /// /// # #[tokio::main(flavor = "current_thread")] /// # async fn main() { /// let mut interval = interval(Duration::from_millis(50)); /// - /// task_that_takes_more_than_50_millis().await; + /// task_that_takes_200_millis().await; /// // The `Interval` has missed a tick /// /// // Since we have exceeded our timeout, this will resolve immediately /// interval.tick().await; /// - /// // If we missed our tick by more than 50ms (if we are over 100ms after - /// // `start`), this will also resolve immediately, otherwise, it will - /// // resolve 100ms after `start`. That is, in `tick`, even though we - /// // recognize that we missed a tick, we schedule the next tick to happen - /// // 50ms (or whatever the `period` is) from when were were *supposed* to - /// // tick + /// // Since we are more than 100ms after the start of `interval`, this will + /// // also resolve immediately. + /// interval.tick().await; + /// + /// // Also resolves immediately, because it was supposed to resolve at + /// // 150ms after the start of `interval` + /// interval.tick().await; + /// + /// // Resolves immediately + /// interval.tick().await; + /// + /// // Since we have gotten to 200ms after the start of `interval`, this + /// // will resolve after 50ms /// interval.tick().await; /// # } /// ``` @@ -268,25 +275,22 @@ pub enum MissedTickBehavior { /// /// ``` /// use tokio::time::{interval, Duration, MissedTickBehavior}; - /// # async fn task_that_takes_more_than_50_millis() {} + /// # async fn task_that_takes_75_millis() {} /// /// # #[tokio::main(flavor = "current_thread")] /// # async fn main() { /// let mut interval = interval(Duration::from_millis(50)); /// interval.set_missed_tick_behavior(MissedTickBehavior::Skip); /// - /// task_that_takes_more_than_50_millis().await; + /// task_that_takes_75_millis().await; /// // The `Interval` has missed a tick /// /// // Since we have exceeded our timeout, this will resolve immediately /// interval.tick().await; /// - /// // This one will resolve at the closest multiple of `period` from - /// // `start` after the call to `tick` up above. That is, in `tick`, when - /// // we recognize that we missed a tick, we schedule the next tick to - /// // happen at the next `period` from `start` that is after right now, - /// // rather than scheduling it to happen one `period` from when were were - /// // *supposed* to tick, or one period after right now. + /// // This one will resolve after 25ms, 100ms after the start of + /// // `interval`, which is the closest multiple of `period` from the start + /// // of `interval` after the call to `tick` up above. /// interval.tick().await; /// # } /// ``` From 75ff91c3049637701314d260fc78167f800cfb36 Mon Sep 17 00:00:00 2001 From: Alice Ryhl Date: Wed, 16 Jun 2021 13:06:01 +0200 Subject: [PATCH 17/17] Update tokio/src/time/interval.rs --- tokio/src/time/interval.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tokio/src/time/interval.rs b/tokio/src/time/interval.rs index 09f8bc07369..a63e47b6ea6 100644 --- a/tokio/src/time/interval.rs +++ b/tokio/src/time/interval.rs @@ -301,7 +301,7 @@ pub enum MissedTickBehavior { } impl MissedTickBehavior { - /// Determine when the next tick should happen. + /// If a tick is missed, this method is called to determine when the next tick should happen. fn next_timeout(&self, timeout: Instant, now: Instant, period: Duration) -> Instant { match self { Self::Burst => timeout + period,