qubit_thread_pool/delayed/scheduled_task.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 ******************************************************************************/
10use std::{
11 cmp::Ordering as CompareOrdering,
12 sync::{
13 Arc,
14 atomic::AtomicU8,
15 },
16 time::Instant,
17};
18
19/// Task stored in the delayed scheduler heap.
20pub struct ScheduledTask {
21 /// Time at which this task becomes runnable.
22 pub deadline: Instant,
23 /// Insertion order used to make equal deadlines deterministic.
24 pub sequence: usize,
25 /// Shared task state observed by cancellation handles.
26 pub state: Arc<AtomicU8>,
27 /// Scheduled action.
28 pub task: Option<Box<dyn FnOnce() + Send + 'static>>,
29}
30
31impl ScheduledTask {
32 /// Creates a heap entry for a delayed task.
33 ///
34 /// # Parameters
35 ///
36 /// * `deadline` - Instant when the task becomes runnable.
37 /// * `sequence` - Stable insertion sequence.
38 /// * `state` - Shared task lifecycle state.
39 /// * `task` - Action to run when the deadline is reached.
40 ///
41 /// # Returns
42 ///
43 /// A scheduled task heap entry.
44 pub fn new(
45 deadline: Instant,
46 sequence: usize,
47 state: Arc<AtomicU8>,
48 task: Box<dyn FnOnce() + Send + 'static>,
49 ) -> Self {
50 Self {
51 deadline,
52 sequence,
53 state,
54 task: Some(task),
55 }
56 }
57}
58
59impl Eq for ScheduledTask {}
60
61impl PartialEq for ScheduledTask {
62 fn eq(&self, other: &Self) -> bool {
63 self.deadline == other.deadline && self.sequence == other.sequence
64 }
65}
66
67impl Ord for ScheduledTask {
68 fn cmp(&self, other: &Self) -> CompareOrdering {
69 other
70 .deadline
71 .cmp(&self.deadline)
72 .then_with(|| other.sequence.cmp(&self.sequence))
73 }
74}
75
76impl PartialOrd for ScheduledTask {
77 fn partial_cmp(&self, other: &Self) -> Option<CompareOrdering> {
78 Some(self.cmp(other))
79 }
80}