Skip to main content

qubit_thread_pool/delayed/
delayed_task_handle.rs

1/*******************************************************************************
2 *
3 *    Copyright (c) 2025 - 2026 Haixing Hu.
4 *
5 *    SPDX-License-Identifier: Apache-2.0
6 *
7 *    Licensed under the Apache License, Version 2.0.
8 *
9 ******************************************************************************/
10//! Cancellation handle for delayed task scheduling.
11
12use std::sync::{
13    Arc,
14    atomic::{
15        AtomicU8,
16        Ordering,
17    },
18};
19
20use super::delayed_task_state::{
21    TASK_CANCELLED,
22    cancel_task_state,
23};
24
25/// Handle that can cancel a delayed task before it starts.
26#[derive(Clone)]
27pub struct DelayedTaskHandle {
28    /// Shared lifecycle state for the scheduled task.
29    state: Arc<AtomicU8>,
30    /// Callback invoked after this handle changes the task to cancelled.
31    on_cancelled: Arc<dyn Fn() + Send + Sync + 'static>,
32}
33
34impl DelayedTaskHandle {
35    /// Creates a delayed task handle.
36    pub(crate) fn new(
37        state: Arc<AtomicU8>,
38        on_cancelled: Arc<dyn Fn() + Send + Sync + 'static>,
39    ) -> Self {
40        Self {
41            state,
42            on_cancelled,
43        }
44    }
45
46    /// Cancels the delayed task if it has not started.
47    ///
48    /// # Returns
49    ///
50    /// `true` if this call cancelled the task.
51    pub fn cancel(&self) -> bool {
52        let cancelled = cancel_task_state(&self.state);
53        if cancelled {
54            (self.on_cancelled)();
55        }
56        cancelled
57    }
58
59    /// Returns whether this delayed task has been cancelled.
60    ///
61    /// # Returns
62    ///
63    /// `true` when the task was cancelled before it started.
64    pub fn is_cancelled(&self) -> bool {
65        self.state.load(Ordering::Acquire) == TASK_CANCELLED
66    }
67}