Skip to content

Commit

Permalink
Improve timer documentation
Browse files Browse the repository at this point in the history
  • Loading branch information
qm3ster committed Aug 20, 2020
1 parent 4a338db commit d20d110
Showing 1 changed file with 9 additions and 5 deletions.
14 changes: 9 additions & 5 deletions src/internal/timer.rs
Original file line number Diff line number Diff line change
@@ -1,13 +1,14 @@
use tokio::time::{delay_until, Duration, Instant};

/// A reusable timer that keeps track of its duration/interval/period.
#[derive(Debug)]
pub struct Timer {
due: Instant,
duration: Duration,
}

impl Timer {
/// construct timer, initially set and due `duration_in_ms` in the future
/// Constructs a `Timer`, initially armed to expire in `duration_in_ms` from the current instant.
pub fn new(duration_in_ms: u64) -> Timer {
let duration = Duration::from_millis(duration_in_ms);

Expand All @@ -17,13 +18,15 @@ impl Timer {
}
}

/// block until next due time resetting afterwards
/// Blocks until the due time.
/// The timer wil be reset afterwards, `duration` later.
pub async fn hold(&mut self) {
delay_until(self.due).await;
self.increment();
}

/// returns true and resets the timer if due
/// Returns true if the timer is expired (current instant past `due` time).
/// Resets the timer `duration` later if it is.
pub fn check(&mut self) -> bool {
if Instant::now() >= self.due {
self.increment();
Expand All @@ -33,12 +36,13 @@ impl Timer {
}
}

/// reset timer to be 1 duration after previous due time
/// Resets the timer to expire 1 `duration` later than the previous due time.
fn increment(&mut self) {
self.due += self.duration
}

/// reset timer to be 1 duration from **now**
/// Resets timer to expire 1 `duration` from the current instant.
/// This has the same effect as constructing a new `Timer` with the same `duration`.
pub fn reset(&mut self) {
self.due = Instant::now() + self.duration;
}
Expand Down

0 comments on commit d20d110

Please sign in to comment.