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,
21	fmt::Debug,
22	sync::{
23		Arc,
24		atomic::{AtomicBool, AtomicU64, Ordering},
25	},
26};
27
28#[cfg(reifydb_target = "native")]
29pub mod scheduler;
30#[cfg(reifydb_target = "wasm")]
31pub(crate) mod wasm;
32
33/// Handle to a scheduled timer.
34///
35/// Can be used to cancel the timer before it fires.
36#[derive(Clone)]
37pub struct TimerHandle {
38	id: u64,
39	cancelled: Arc<AtomicBool>,
40}
41
42impl TimerHandle {
43	pub(crate) fn new(id: u64) -> Self {
44		Self {
45			id,
46			cancelled: Arc::new(AtomicBool::new(false)),
47		}
48	}
49
50	/// Cancel this timer.
51	///
52	/// If the timer hasn't fired yet, it will be cancelled.
53	/// Returns `true` if the timer was successfully cancelled.
54	pub fn cancel(&self) -> bool {
55		self.cancelled.compare_exchange(false, true, Ordering::SeqCst, Ordering::SeqCst).is_ok()
56	}
57
58	/// Check if this timer has been cancelled.
59	pub fn is_cancelled(&self) -> bool {
60		self.cancelled.load(Ordering::SeqCst)
61	}
62
63	/// Get the timer ID.
64	pub fn id(&self) -> u64 {
65		self.id
66	}
67
68	/// Get a clone of the cancelled flag.
69	pub(crate) fn cancelled_flag(&self) -> Arc<AtomicBool> {
70		self.cancelled.clone()
71	}
72}
73
74impl Debug for TimerHandle {
75	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
76		f.debug_struct("TimerHandle").field("id", &self.id).field("cancelled", &self.is_cancelled()).finish()
77	}
78}
79
80/// Counter for generating unique timer IDs.
81static TIMER_ID_COUNTER: AtomicU64 = AtomicU64::new(0);
82
83pub(crate) fn next_timer_id() -> u64 {
84	TIMER_ID_COUNTER.fetch_add(1, Ordering::Relaxed)
85}