Skip to main content

reifydb_runtime/actor/timers/
mod.rs

1// SPDX-License-Identifier: AGPL-3.0-or-later
2// Copyright (c) 2025 ReifyDB
3
4//! Timer utilities for actors.
5//!
6//! This module provides timer functionality for scheduling messages:
7//! - [`TimerHandle`]: A handle to cancel a scheduled timer
8//! - [`Context::schedule_once`]: Schedule a message to be sent after a delay
9//! - [`Context::schedule_repeat`]: Schedule a message to be sent repeatedly
10//!
11//! # Platform Differences
12//!
13//! - **Native**: Uses a centralized scheduler with a BinaryHeap min-heap
14//! - **WASM**: Uses `setTimeout` and `setInterval` via `web-sys`
15//!
16//! [`Context::schedule_once`]: crate::actor::context::Context::schedule_once
17//! [`Context::schedule_repeat`]: crate::actor::context::Context::schedule_repeat
18
19use std::{
20	fmt::Debug,
21	sync::{
22		Arc,
23		atomic::{AtomicBool, AtomicU64, Ordering},
24	},
25};
26
27#[cfg(reifydb_target = "native")]
28pub mod scheduler;
29#[cfg(reifydb_target = "wasm")]
30pub(crate) mod wasm;
31
32/// Handle to a scheduled timer.
33///
34/// Can be used to cancel the timer before it fires.
35#[derive(Clone)]
36pub struct TimerHandle {
37	id: u64,
38	cancelled: Arc<AtomicBool>,
39}
40
41impl TimerHandle {
42	pub(crate) fn new(id: u64) -> Self {
43		Self {
44			id,
45			cancelled: Arc::new(AtomicBool::new(false)),
46		}
47	}
48
49	/// Cancel this timer.
50	///
51	/// If the timer hasn't fired yet, it will be cancelled.
52	/// Returns `true` if the timer was successfully cancelled.
53	pub fn cancel(&self) -> bool {
54		self.cancelled.compare_exchange(false, true, Ordering::SeqCst, Ordering::SeqCst).is_ok()
55	}
56
57	/// Check if this timer has been cancelled.
58	pub fn is_cancelled(&self) -> bool {
59		self.cancelled.load(Ordering::SeqCst)
60	}
61
62	/// Get the timer ID.
63	pub fn id(&self) -> u64 {
64		self.id
65	}
66
67	/// Get a clone of the cancelled flag.
68	pub(crate) fn cancelled_flag(&self) -> Arc<AtomicBool> {
69		self.cancelled.clone()
70	}
71}
72
73impl Debug for TimerHandle {
74	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
75		f.debug_struct("TimerHandle").field("id", &self.id).field("cancelled", &self.is_cancelled()).finish()
76	}
77}
78
79/// Counter for generating unique timer IDs.
80static TIMER_ID_COUNTER: AtomicU64 = AtomicU64::new(0);
81
82pub(crate) fn next_timer_id() -> u64 {
83	TIMER_ID_COUNTER.fetch_add(1, Ordering::Relaxed)
84}