2020-04-19 19:13:04 +00:00
|
|
|
use super::{App, AppBuilder, AppPlugin, GetEventReader};
|
|
|
|
use crate::{AppExit, Events};
|
2020-03-30 18:52:33 +00:00
|
|
|
use std::{thread, time::Duration};
|
|
|
|
|
|
|
|
#[derive(Copy, Clone, Debug)]
|
|
|
|
pub enum RunMode {
|
2020-04-04 19:43:16 +00:00
|
|
|
Loop { wait: Option<Duration> },
|
2020-03-30 18:52:33 +00:00
|
|
|
Once,
|
|
|
|
}
|
|
|
|
|
|
|
|
impl Default for RunMode {
|
|
|
|
fn default() -> Self {
|
2020-04-04 19:43:16 +00:00
|
|
|
RunMode::Loop { wait: None }
|
2020-03-30 18:52:33 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
#[derive(Default)]
|
2020-04-04 20:00:52 +00:00
|
|
|
pub struct ScheduleRunnerPlugin {
|
2020-03-30 18:52:33 +00:00
|
|
|
pub run_mode: RunMode,
|
|
|
|
}
|
|
|
|
|
2020-04-04 20:00:52 +00:00
|
|
|
impl AppPlugin for ScheduleRunnerPlugin {
|
2020-04-06 03:19:02 +00:00
|
|
|
fn build(&self, app: &mut AppBuilder) {
|
2020-03-30 18:52:33 +00:00
|
|
|
let run_mode = self.run_mode;
|
2020-04-19 19:13:04 +00:00
|
|
|
app.set_runner(move |mut app: App| {
|
|
|
|
let mut app_exit_event_reader = app.resources.get_event_reader::<AppExit>();
|
|
|
|
match run_mode {
|
|
|
|
RunMode::Once => {
|
|
|
|
if let Some(ref mut schedule) = app.schedule {
|
|
|
|
schedule.execute(&mut app.world, &mut app.resources);
|
|
|
|
}
|
2020-04-06 03:19:02 +00:00
|
|
|
}
|
2020-04-19 19:13:04 +00:00
|
|
|
RunMode::Loop { wait } => loop {
|
|
|
|
if let Some(app_exit_events) = app.resources.get_mut::<Events<AppExit>>() {
|
|
|
|
if app_exit_events.latest(&mut app_exit_event_reader).is_some() {
|
|
|
|
break;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
if let Some(ref mut schedule) = app.schedule {
|
|
|
|
schedule.execute(&mut app.world, &mut app.resources);
|
|
|
|
}
|
|
|
|
if let Some(wait) = wait {
|
|
|
|
thread::sleep(wait);
|
|
|
|
}
|
|
|
|
},
|
2020-03-30 18:52:33 +00:00
|
|
|
}
|
2020-04-06 03:19:02 +00:00
|
|
|
});
|
2020-03-30 18:52:33 +00:00
|
|
|
}
|
|
|
|
}
|