1use super::{TaskStatus, TaskType};
6use core::cmp::Ordering;
7use std::time::{Duration, Instant};
8
9#[derive(Clone, Debug, Eq, PartialEq)]
11pub struct Task {
12 pub(crate) id: usize,
14 pub(crate) priority: usize,
16 pub(crate) effective_priority: usize,
18 pub(crate) created_at: Instant,
20 pub(crate) started_at: Option<Instant>,
22 pub(crate) completed_at: Option<Instant>,
24 pub(crate) scheduled_delay: Option<Duration>,
26 pub(crate) kind: TaskType,
28 pub(crate) status: TaskStatus,
30}
31
32impl Task {
33 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 pub fn mark_started(&mut self) {
50 self.started_at = Some(Instant::now());
51 self.status = TaskStatus::Running;
52 }
53
54 pub fn mark_completed(&mut self) {
56 self.completed_at = Some(Instant::now());
57 self.status = TaskStatus::Completed;
58 }
59
60 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
67impl Ord for Task {
69 fn cmp(&self, other: &Self) -> Ordering {
70 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}