1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331
use std::collections::hash_map::Entry; use std::collections::HashMap; use ic_cdk::export::candid::{CandidType, Result as CandidResult}; use crate::types::{ Iterations, ScheduledTask, SchedulingInterval, TaskExecutionQueue, TaskId, TaskTimestamp, }; #[derive(Default)] pub struct TaskScheduler { pub is_running: bool, pub tasks: HashMap<TaskId, ScheduledTask>, pub task_id_counter: TaskId, pub queue: TaskExecutionQueue, } impl TaskScheduler { pub fn enqueue<TaskPayload: CandidType>( &mut self, kind: u8, payload: TaskPayload, scheduling_interval: SchedulingInterval, timestamp: u64, ) -> CandidResult<TaskId> { let id = self.generate_task_id(); let task = ScheduledTask::new(id, kind, payload, timestamp, None, scheduling_interval)?; match task.scheduling_interval.iterations { Iterations::Exact(times) => { if times > 0 { self.queue.push(TaskTimestamp { task_id: id, timestamp: timestamp + task.scheduling_interval.duration_nano, }) } } Iterations::Infinite => self.queue.push(TaskTimestamp { task_id: id, timestamp: timestamp + task.scheduling_interval.duration_nano, }), }; self.tasks.insert(id, task); self.try_start(); Ok(id) } pub fn iterate(&mut self, timestamp: u64) -> Vec<ScheduledTask> { let mut tasks = vec![]; for task_id in self .queue .pop_ready(timestamp) .into_iter() .map(|it| it.task_id) { let mut should_remove = false; match self.tasks.entry(task_id) { Entry::Occupied(mut entry) => { let task = entry.get_mut(); match task.scheduling_interval.iterations { Iterations::Infinite => { let new_rescheduled_at = if let Some(rescheduled_at) = task.rescheduled_at { rescheduled_at + task.scheduling_interval.duration_nano } else { task.scheduled_at + task.scheduling_interval.duration_nano }; task.rescheduled_at = Some(new_rescheduled_at); self.queue.push(TaskTimestamp { task_id, timestamp: new_rescheduled_at + task.scheduling_interval.duration_nano, }); } Iterations::Exact(times_left) => { if times_left > 1 { let new_rescheduled_at = if let Some(rescheduled_at) = task.rescheduled_at { rescheduled_at + task.scheduling_interval.duration_nano } else { task.scheduled_at + task.scheduling_interval.duration_nano }; task.rescheduled_at = Some(new_rescheduled_at); self.queue.push(TaskTimestamp { task_id, timestamp: new_rescheduled_at + task.scheduling_interval.duration_nano, }); task.scheduling_interval.iterations = Iterations::Exact(times_left - 1); } else { should_remove = true; } } }; tasks.push(task.clone()); } Entry::Vacant(_) => {} } if should_remove { self.tasks.remove(&task_id); } } tasks } pub fn dequeue(&mut self, task_id: TaskId) -> Option<ScheduledTask> { let task = self.tasks.remove(&task_id); self.try_stop(); task } pub fn is_empty(&self) -> bool { self.queue.is_empty() } pub fn get_task_by_id(&self, task_id: &TaskId) -> Option<ScheduledTask> { self.tasks.get(task_id).cloned() } pub fn get_tasks(&self) -> Vec<ScheduledTask> { self.tasks.values().cloned().collect() } fn generate_task_id(&mut self) -> TaskId { let res = self.task_id_counter; self.task_id_counter += 1; res } pub fn try_start(&mut self) -> bool { if !self.is_running { self.is_running = true; true } else { false } } pub fn try_stop(&mut self) -> bool { if !self.is_running { true } else if self.tasks.is_empty() { self.is_running = false; true } else { false } } } #[cfg(test)] mod tests { use ic_cdk::export::candid::{CandidType, Deserialize}; use crate::task_scheduler::TaskScheduler; use crate::types::{Iterations, SchedulingInterval}; #[derive(CandidType, Deserialize)] pub struct TestPayload { pub a: bool, } #[test] fn main_flow_works_fine() { let mut scheduler = TaskScheduler::default(); let task_id_1 = scheduler .enqueue( 0, TestPayload { a: true }, SchedulingInterval { duration_nano: 10, iterations: Iterations::Exact(1), }, 0, ) .ok() .unwrap(); let task_id_2 = scheduler .enqueue( 1, TestPayload { a: true }, SchedulingInterval { duration_nano: 10, iterations: Iterations::Infinite, }, 0, ) .ok() .unwrap(); let task_id_3 = scheduler .enqueue( 0, TestPayload { a: false }, SchedulingInterval { duration_nano: 20, iterations: Iterations::Exact(2), }, 0, ) .ok() .unwrap(); assert!(!scheduler.is_empty(), "Scheduler is not empty"); assert!(scheduler.is_running, "Scheduler should run"); let tasks_emp = scheduler.iterate(5); assert!( tasks_emp.is_empty(), "There should not be any tasks at timestamp 5" ); let tasks_1_2 = scheduler.iterate(10); assert_eq!( tasks_1_2.len(), 2, "At timestamp 10 there should be 2 tasks" ); assert!( tasks_1_2.iter().any(|t| t.id == task_id_1), "Should contain task 1" ); assert!( tasks_1_2.iter().any(|t| t.id == task_id_2), "Should contain task 2" ); let tasks_emp = scheduler.iterate(15); assert!( tasks_emp.is_empty(), "There should not be any tasks at timestamp 15" ); let tasks_2_3 = scheduler.iterate(20); assert_eq!( tasks_2_3.len(), 2, "At timestamp 20 there should be 2 tasks" ); assert!( tasks_2_3.iter().any(|t| t.id == task_id_2), "Should contain task 2" ); assert!( tasks_2_3.iter().any(|t| t.id == task_id_3), "Should contain task 3" ); let tasks_2 = scheduler.iterate(30); assert_eq!( tasks_2.len(), 1, "There should be a single task at timestamp 30" ); assert_eq!(tasks_2[0].id, task_id_2, "Should contain task 2"); let tasks_2_3 = scheduler.iterate(42); assert_eq!( tasks_2_3.len(), 2, "At timestamp 40 there should be 2 tasks" ); assert!( tasks_2_3.iter().any(|t| t.id == task_id_2), "Should contain task 2" ); assert!( tasks_2_3.iter().any(|t| t.id == task_id_3), "Should contain task 3" ); let tasks_2 = scheduler.iterate(55); assert_eq!( tasks_2.len(), 1, "There should be a single task at timestamp 60" ); assert_eq!(tasks_2[0].id, task_id_2, "Should contain task 2"); let tasks_2 = scheduler.iterate(60); assert_eq!( tasks_2.len(), 1, "There should be a single task at timestamp 60" ); assert_eq!(tasks_2[0].id, task_id_2, "Should contain task 2"); scheduler.dequeue(task_id_2).unwrap(); assert!(!scheduler.is_running, "Scheduler should stop"); scheduler .enqueue( 0, TestPayload { a: true }, SchedulingInterval { duration_nano: 10, iterations: Iterations::Exact(1), }, 0, ) .ok() .unwrap(); assert!(scheduler.is_running, "Scheduler should start again"); } }