Start the scheduler and begin processing tasks
(
&mut self,
workers: u32,
)
| 316 | |
| 317 | /// Start the scheduler and begin processing tasks |
| 318 | pub async fn start( |
| 319 | &mut self, |
| 320 | workers: u32, |
| 321 | ) -> Result<(), Box<dyn std::error::Error + Send + Sync>> { |
| 322 | let mut running = self.running.lock().await; |
| 323 | if *running { |
| 324 | return Err("Scheduler is already running".into()); |
| 325 | } |
| 326 | *running = true; |
| 327 | drop(running); |
| 328 | |
| 329 | self.emit(ServerEvent::StatusMessage(format!( |
| 330 | "Task scheduler started with {} worker(s)", |
| 331 | workers |
| 332 | ))); |
| 333 | |
| 334 | if self.quit_when_done { |
| 335 | self.emit(ServerEvent::StatusMessage( |
| 336 | "Running in quit-when-done mode - will exit when queue is empty".to_string(), |
| 337 | )); |
| 338 | } |
| 339 | |
| 340 | // Create the worker pool |
| 341 | let worker_pool = Arc::new(WorkerPool::<TaskJob>::new(workers as usize)); |
| 342 | self.worker_pool = Some(worker_pool.clone()); |
| 343 | |
| 344 | // Set initial idle title |
| 345 | self.update_terminal_title(); |
| 346 | |
| 347 | // Check if we should quit immediately due to empty queue |
| 348 | if self.quit_when_done { |
| 349 | let tasks = self.storage.list_tasks().await?; |
| 350 | |
| 351 | let queued_count = tasks |
| 352 | .iter() |
| 353 | .filter(|t| t.status == TaskStatus::Queued) |
| 354 | .count(); |
| 355 | |
| 356 | if queued_count == 0 { |
| 357 | self.emit(ServerEvent::StatusMessage( |
| 358 | "Queue is empty at startup. Exiting immediately...".to_string(), |
| 359 | )); |
| 360 | self.quit_signal.notify_one(); |
| 361 | self.stop().await; |
| 362 | // Loop will check running flag and exit immediately |
| 363 | } |
| 364 | } |
| 365 | |
| 366 | // Main scheduling loop |
| 367 | loop { |
| 368 | // Check if we should continue running |
| 369 | if !*self.running.lock().await { |
| 370 | self.emit(ServerEvent::StatusMessage( |
| 371 | "Task scheduler stopping, waiting for active tasks to complete...".to_string(), |
| 372 | )); |
| 373 | |
| 374 | // Shutdown the worker pool and wait for all tasks |
| 375 | if let Some(pool) = &self.worker_pool { |