pub trait Clock: Send + Sync {
// Required methods
fn now(&self) -> Monotonic;
fn wall(&self) -> Wall;
}Available on crate feature
std only.Expand description
A source of time.
Clock exposes both kinds of reading clock-lib draws apart:
a monotonic reading via Clock::now and a wall-clock reading via
Clock::wall. Implementations must be safe to share across threads.
In production, take a Clock (or &dyn Clock, or Arc<dyn Clock>) as
a dependency and use SystemClock at the top of your call graph. In
tests, substitute ManualClock and drive time forward by calling
ManualClock::advance.
Clock is also implemented for Arc<C> and &C where C: Clock,
so the same value can be shared and reused freely.
§Examples
use clock_lib::{Clock, ManualClock, SystemClock};
use std::time::Duration;
fn took_at_least<C: Clock>(clock: &C, start: clock_lib::Monotonic, target: Duration) -> bool {
clock.now().duration_since(start) >= target
}
// Production
let sys = SystemClock::new();
let start = sys.now();
assert!(!took_at_least(&sys, start, Duration::from_secs(60 * 60)));
// Test — no sleep, fully deterministic
let test = ManualClock::new();
let start = test.now();
test.advance(Duration::from_secs(60 * 60));
assert!(took_at_least(&test, start, Duration::from_secs(60 * 60)));