canic_core/interface/ic/
timer.rs

1use crate::{
2    cdk::timers::{
3        clear_timer as cdk_clear_timer, set_timer as cdk_set_timer,
4        set_timer_interval as cdk_set_timer_interval,
5    },
6    model::metrics::{SystemMetricKind, SystemMetrics, TimerMetrics, TimerMode},
7};
8
9pub use crate::cdk::timers::TimerId;
10use std::{future::Future, time::Duration};
11
12///
13/// Timer
14///
15
16pub struct Timer;
17
18impl Timer {
19    /// Schedule a one-shot timer and record metrics.
20    pub fn set(delay: Duration, label: &str, task: impl Future<Output = ()> + 'static) -> TimerId {
21        SystemMetrics::increment(SystemMetricKind::TimerScheduled);
22        TimerMetrics::increment(TimerMode::Once, delay, label);
23
24        cdk_set_timer(delay, task)
25    }
26
27    /// Schedule a repeating timer and record metrics.
28    pub fn set_interval<F, Fut>(interval: Duration, label: &str, task: F) -> TimerId
29    where
30        F: FnMut() -> Fut + 'static,
31        Fut: Future<Output = ()> + 'static,
32    {
33        SystemMetrics::increment(SystemMetricKind::TimerScheduled);
34        TimerMetrics::increment(TimerMode::Interval, interval, label);
35
36        cdk_set_timer_interval(interval, task)
37    }
38
39    /// Clear a timer without recording metrics.
40    pub fn clear(id: TimerId) {
41        cdk_clear_timer(id);
42    }
43}