Skip to content

Commit

Permalink
implement extra reset variants for Interval
Browse files Browse the repository at this point in the history
Fixes: #5874
  • Loading branch information
victor-timofei committed Jul 18, 2023
1 parent 267a231 commit 77b08c7
Showing 1 changed file with 97 additions and 0 deletions.
97 changes: 97 additions & 0 deletions tokio/src/time/interval.rs
Original file line number Diff line number Diff line change
Expand Up @@ -521,6 +521,103 @@ impl Interval {
self.delay.as_mut().reset(Instant::now() + self.period);
}

/// Resets the interval immediately.
///
/// This method ignores [`MissedTickBehavior`] strategy.
///
/// # Examples
///
/// ```
/// use tokio::time;
///
/// use std::time::Duration;
///
/// #[tokio::main]
/// async fn main() {
/// let mut interval = time::interval(Duration::from_millis(100));
///
/// interval.tick().await;
///
/// time::sleep(Duration::from_millis(50)).await;
/// interval.reset_immediately();
///
/// interval.tick().await;
/// interval.tick().await;
///
/// // approximately 150ms have elapsed.
/// }
/// ```
pub fn reset_immediately(&mut self) {
self.delay.as_mut().reset(Instant::now());
}

/// Resets the interval after the specified [`std::time::Duration`].
///
/// This method ignores [`MissedTickBehavior`] strategy.
///
/// # Examples
///
/// ```
/// use tokio::time;
///
/// use std::time::Duration;
///
/// #[tokio::main]
/// async fn main() {
/// let mut interval = time::interval(Duration::from_millis(100));
/// interval.tick().await;
///
/// time::sleep(Duration::from_millis(50)).await;
///
/// let after = Duration::from_millis(20);
/// interval.reset_after(after);
///
/// interval.tick().await;
/// interval.tick().await;
///
/// // approximately 170ms have elapsed.
/// }
/// ```
pub fn reset_after(&mut self, after: Duration) {
self.delay.as_mut().reset(Instant::now() + after);
}

/// Resets the interval to a [`crate::time::instant::Instant`] deadline.
/// If deadline is in the past it behaves like `reset_immediately`.
///
/// This method ignores [`MissedTickBehavior`] strategy.
///
/// # Examples
///
/// ```
/// use tokio::time::{self, Instant};
///
/// use std::time::Duration;
///
/// #[tokio::main]
/// async fn main() {
/// let mut interval = time::interval(Duration::from_millis(100));
/// interval.tick().await;
///
/// time::sleep(Duration::from_millis(50)).await;
///
/// let deadline = Instant::now() + Duration::from_millis(30);
/// interval.reset_at(deadline);
///
/// interval.tick().await;
/// interval.tick().await;
///
/// // approximately 180ms have elapsed.
/// }
/// ```
pub fn reset_at(&mut self, deadline: Instant) {
if deadline > Instant::now() {
self.delay.as_mut().reset(deadline);
} else {
self.reset_immediately();
}
}

/// Returns the [`MissedTickBehavior`] strategy currently being used.
pub fn missed_tick_behavior(&self) -> MissedTickBehavior {
self.missed_tick_behavior
Expand Down

0 comments on commit 77b08c7

Please sign in to comment.