diff --git a/src/task.rs b/src/task.rs index a7504e2..e9900e4 100644 --- a/src/task.rs +++ b/src/task.rs @@ -9,81 +9,16 @@ pub trait Task: core::fmt::Debug { } } -trait ScheduledState: std::fmt::Debug { - fn start(self: Box) -> Box; - fn stop(self: Box) -> Box; - fn tick(self: Box, task: &mut dyn Task) -> Box; -} - -#[derive(Debug)] -struct Starting {} -impl ScheduledState for Starting { - fn start(self: Box) -> Box { - self - } - - fn stop(self: Box) -> Box { - Box::new(Stopped {}) - } - - fn tick(self: Box, task: &mut dyn Task) -> Box { - task.start(); - Box::new(Running{}) - } -} - -#[derive(Debug)] -struct Running {} -impl ScheduledState for Running { - fn start(self: Box) -> Box { - self - } - - fn stop(self: Box) -> Box { - Box::new(Stopping {}) - } - - fn tick(self: Box, task: &mut dyn Task) -> Box { - task.tick(); - self - } -} - -#[derive(Debug)] -struct Stopping {} -impl ScheduledState for Stopping { - fn start(self: Box) -> Box { - Box::new(Running {}) - } - - fn stop(self: Box) -> Box { - self - } - - fn tick(self: Box, task: &mut dyn Task) -> Box { - task.stop(); - Box::new(Stopped {}) - } -} - -#[derive(Debug)] -struct Stopped {} -impl ScheduledState for Stopped { - fn start(self: Box) -> Box { - Box::new(Starting {}) - } - - fn stop(self: Box) -> Box { - self - } - - fn tick(self: Box, _task: &mut dyn Task) -> Box { - self - } +#[derive(Debug, Copy, Clone)] +enum ScheduledState { + Stopped, + Start, + Running, + Stop } struct ScheduledTask { - state: Option>, + state: ScheduledState, task: Box, } @@ -99,26 +34,44 @@ impl std::fmt::Debug for ScheduledTask { impl ScheduledTask { fn new(task: Box) -> Self { ScheduledTask { - state: Some(Box::new(Starting{})), + state: ScheduledState::Start, task: task, } } fn start(&mut self) { - if let Some(s) = self.state.take() { - self.state = Some(s.start()); + self.state = match self.state { + ScheduledState::Stopped => ScheduledState::Start, + ScheduledState::Stop => ScheduledState::Running, + _ => self.state } } fn stop(&mut self) { - if let Some(s) = self.state.take() { - self.state = Some(s.stop()); + self.state = match self.state { + ScheduledState::Running => ScheduledState::Stop, + ScheduledState::Start => ScheduledState::Stopped, + _ => self.state } } fn tick(&mut self) { - if let Some(s) = self.state.take() { - self.state = Some(s.tick(self.task.as_mut())); + self.state = match self.state { + ScheduledState::Start => { + log::info!("Starting task {}", self.task.name()); + self.task.start(); + ScheduledState::Running + }, + ScheduledState::Running => { + self.task.tick(); + ScheduledState::Running + }, + ScheduledState::Stop => { + log::info!("Stopping task {}", self.task.name()); + self.task.stop(); + ScheduledState::Stopped + }, + ScheduledState::Stopped => ScheduledState::Stopped } } }