Skip to main content

canic_core/api/
timer.rs

1//! Module: api::timer
2//!
3//! Responsibility: expose the maintained application and lifecycle timer facade.
4//! Does not own: timer state, recurrence, arbitration, or domain scheduling policy.
5//! Boundary: macro-expanded downstream code delegates to TimerWorkflow.
6
7use crate::workflow::runtime::timer::{ApplicationTimerId, TimerWorkflow};
8use std::{future::Future, time::Duration};
9
10/// Opaque, single-owner handle for a cancellable application timer.
11#[derive(Debug, Eq, PartialEq)]
12pub struct TimerHandle(ApplicationTimerId);
13
14/// Public timer facade used by Canic's macro-expanded entrypoints.
15pub struct TimerApi;
16
17impl TimerApi {
18    /// Schedule a cancellable application one-shot.
19    pub fn set(
20        delay: Duration,
21        label: impl Into<String>,
22        task: impl Future<Output = ()> + 'static,
23    ) -> TimerHandle {
24        TimerHandle(TimerWorkflow::set_application_once(delay, label, task))
25    }
26
27    /// Defer lifecycle work through the same one-shot authority.
28    pub fn defer_lifecycle(
29        delay: Duration,
30        label: impl Into<String>,
31        task: impl Future<Output = ()> + 'static,
32    ) -> TimerHandle {
33        Self::set(delay, label, task)
34    }
35
36    /// Schedule a cancellable, non-overlapping after-completion interval.
37    pub fn set_interval<F, Fut>(
38        interval: Duration,
39        label: impl Into<String>,
40        task: F,
41    ) -> TimerHandle
42    where
43        F: FnMut() -> Fut + 'static,
44        Fut: Future<Output = ()> + 'static,
45    {
46        TimerHandle(TimerWorkflow::set_application_interval(
47            interval, label, task,
48        ))
49    }
50
51    /// Consume a timer handle and suppress any future invocation.
52    #[must_use]
53    pub fn cancel(handle: TimerHandle) -> bool {
54        TimerWorkflow::cancel_application(handle.0)
55    }
56}