renderbug/src/task.rs

102 lines
2.4 KiB
Rust
Raw Normal View History

use core::fmt;
pub trait Task: core::fmt::Debug {
fn tick(&mut self) {}
fn start(&mut self) {}
fn stop(&mut self) {}
2024-11-02 15:18:15 +01:00
fn name(&self) -> &'static str {
core::any::type_name::<Self>()
}
}
#[derive(Debug, Copy, Clone)]
enum ScheduledState {
Stopped,
Start,
Running,
Stop
}
struct ScheduledTask {
state: ScheduledState,
task: Box<dyn Task>,
}
impl std::fmt::Debug for ScheduledTask {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("ScheduledTask")
.field("task", &self.task.name())
.field("state", &self.state)
.finish()
}
}
impl ScheduledTask {
fn new(task: Box<dyn Task>) -> Self {
ScheduledTask {
state: ScheduledState::Start,
task: task,
}
}
fn start(&mut self) {
self.state = match self.state {
ScheduledState::Stopped => ScheduledState::Start,
ScheduledState::Stop => ScheduledState::Running,
_ => self.state
}
}
fn stop(&mut self) {
self.state = match self.state {
ScheduledState::Running => ScheduledState::Stop,
ScheduledState::Start => ScheduledState::Stopped,
_ => self.state
}
}
fn tick(&mut self) {
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
}
}
}
2024-11-02 15:21:30 +01:00
#[derive(Debug)]
pub struct Scheduler {
tasks: Vec<ScheduledTask>,
}
impl Scheduler {
pub fn new(tasks: Vec<Box<dyn Task>>) -> Self {
let mut scheduled = Vec::new();
for task in tasks {
2024-11-02 15:21:30 +01:00
log::info!("Scheduling task {} {:?}", task.name(), task);
scheduled.push(ScheduledTask::new(task));
}
Scheduler {
tasks: scheduled
}
}
pub fn tick(&mut self) {
for task in &mut self.tasks {
task.tick();
}
}
}