Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Remove some chrono #933

Merged
merged 2 commits into from
Aug 20, 2020
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
51 changes: 25 additions & 26 deletions src/internal/timer.rs
Original file line number Diff line number Diff line change
@@ -1,51 +1,50 @@
use chrono::{DateTime, Duration, Utc};
use std::time::Duration as StdDuration;
use tokio::time::delay_for;
use tokio::time::{delay_until, Duration, Instant};

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

impl Timer {
/// 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::milliseconds(duration_in_ms as i64);
let duration = Duration::from_millis(duration_in_ms);

Timer {
due: Utc::now() + duration,
due: Instant::now() + duration,
duration,
}
}

/// Blocks until the due time.
/// The timer wil be reset afterwards, `duration` later.
pub async fn hold(&mut self) {
let due_time = (self.due.timestamp() * 1000) + i64::from(self.due.timestamp_subsec_millis());
let now_time = {
let now = Utc::now();

(now.timestamp() * 1000) + i64::from(now.timestamp_subsec_millis())
};

if due_time > now_time {
let sleep_time = due_time - now_time;

if sleep_time > 0 {
delay_for(StdDuration::from_millis(sleep_time as u64)).await;
}
}

self.due = self.due + self.duration;
delay_until(self.due).await;
self.increment();
}

/// 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 Utc::now() >= self.due {
self.due = self.due + self.duration;

if Instant::now() >= self.due {
self.increment();
true
} else {
false
}
}

pub fn reset(&mut self) { self.due = Utc::now() + self.duration; }
/// Resets the timer to expire 1 `duration` later than it was **previously set to expire**.
/// Does not depend on the actual current time.
fn increment(&mut self) {
self.due += self.duration
}

/// 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;
}
}