eryon_rt/tasks/
task.rs

1/*
2    Appellation: task <module>
3    Contrib: @FL03
4*/
5use super::{TaskStatus, TaskType};
6use core::cmp::Ordering;
7use std::time::{Duration, Instant};
8
9/// A task that can be scheduled for execution
10#[derive(Clone, Debug, Eq, PartialEq)]
11pub struct Task {
12    /// Unique identifier for the task
13    pub(crate) id: usize,
14    /// Priority level (higher = more important)
15    pub(crate) priority: usize,
16    /// Effective priority after adjustments
17    pub(crate) effective_priority: usize,
18    /// When the task was created
19    pub(crate) created_at: Instant,
20    /// When the task started execution
21    pub(crate) started_at: Option<Instant>,
22    /// When the task completed execution
23    pub(crate) completed_at: Option<Instant>,
24    /// Scheduled delay for execution
25    pub(crate) scheduled_delay: Option<Duration>,
26    /// Type of task
27    pub(crate) kind: TaskType,
28    /// Task status
29    pub(crate) status: TaskStatus,
30}
31
32impl Task {
33    /// Create a new task
34    pub fn new(id: usize, priority: usize, kind: TaskType) -> Self {
35        Self {
36            id,
37            priority,
38            effective_priority: priority,
39            created_at: Instant::now(),
40            started_at: None,
41            completed_at: None,
42            scheduled_delay: None,
43            kind,
44            status: TaskStatus::Queued,
45        }
46    }
47
48    /// Mark the task as started
49    pub fn mark_started(&mut self) {
50        self.started_at = Some(Instant::now());
51        self.status = TaskStatus::Running;
52    }
53
54    /// Mark the task as completed
55    pub fn mark_completed(&mut self) {
56        self.completed_at = Some(Instant::now());
57        self.status = TaskStatus::Completed;
58    }
59
60    /// Mark the task as failed
61    pub fn mark_failed(&mut self, error: impl Into<String>) {
62        self.completed_at = Some(Instant::now());
63        self.status = TaskStatus::Failed(error.into());
64    }
65}
66
67// Make Task comparable for the priority queue
68impl Ord for Task {
69    fn cmp(&self, other: &Self) -> Ordering {
70        // First compare by effective priority (higher first)
71        self.effective_priority
72            .cmp(&other.effective_priority)
73            .then(other.created_at.cmp(&self.created_at))
74            .then(self.id.cmp(&other.id))
75    }
76}
77
78impl PartialOrd for Task {
79    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
80        Some(self.cmp(other))
81    }
82}