forked from lovasoa/dezoomify-rs
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy paththrottler.rs
More file actions
28 lines (25 loc) · 692 Bytes
/
throttler.rs
File metadata and controls
28 lines (25 loc) · 692 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
use std::time::{Duration, Instant};
pub struct Throttler {
last_update: Instant,
min_interval: Duration,
}
impl Throttler {
pub fn new(min_interval: Duration) -> Self {
Self {
last_update: Instant::now(),
min_interval,
}
}
pub async fn wait(&mut self) {
if self.min_interval.is_zero() {
return;
}
let now = Instant::now();
let next_allowed = self.last_update + self.min_interval;
self.last_update = now;
let sleep_time = next_allowed.saturating_duration_since(now);
if !sleep_time.is_zero() {
tokio::time::sleep(sleep_time).await;
}
}
}