use std::time::Duration;
use futures::StreamExt;
use tick::fmt::Iso8601;
use tick::{Clock, FutureExt, PeriodicTimer};
#[tokio::main]
async fn main() -> Result<(), ohno::AppError> {
let clock = Clock::new_tokio();
let api = MyApi::new(&clock);
api.do_something().await;
let timer = PeriodicTimer::new(&clock, Duration::from_secs(2));
timer
.take(3)
.for_each(async |()| {
println!("Timer fired in background!");
})
.await;
match clock.delay(Duration::from_secs(30)).timeout(&clock, Duration::from_secs(2)).await {
Ok(()) => println!("Background job completed within the timeout."),
Err(error) => println!("Background job timed out. Error: {error}"),
}
Ok(())
}
struct MyApi {
clock: Clock,
}
impl MyApi {
fn new(clock: &Clock) -> Self {
Self { clock: clock.clone() }
}
pub async fn do_something(&self) {
let watch = self.clock.stopwatch();
self.clock.delay(Duration::from_millis(10)).await;
println!(
"Work done. Elapsed: {}ms, Timestamp: {}",
watch.elapsed().as_millis(),
self.clock.system_time_as::<Iso8601>()
);
}
}