use std::time::{Duration, Instant};
use bevy::{prelude::*, MinimalPlugins};
use bevy_app::{App, AppExit};
use bevy_background_compute::{
BackgroundComputeCheck, BackgroundComputeComplete, BackgroundComputePlugin,
ComputeInBackgroundCommandExt,
};
use bevy_ecs::schedule::IntoSystemConfigs;
#[derive(Debug)]
struct FunnyNumber(i32);
fn main() {
App::new()
.add_plugins(MinimalPlugins)
.add_plugins(BackgroundComputePlugin::<FunnyNumber>::default())
.add_systems(Startup, start_background_compute)
.add_systems(
Update,
background_compute_callback
.after(BackgroundComputeCheck::<FunnyNumber>::default()),
)
.run();
}
fn start_background_compute(mut commands: Commands) {
println!("Starting background compute");
commands.compute_in_background(async move {
let start_time = Instant::now();
let duration = Duration::from_secs(5);
while start_time.elapsed() < duration {
}
FunnyNumber(69)
});
println!("Returning from starting compute");
}
fn background_compute_callback(
mut events: EventReader<BackgroundComputeComplete<FunnyNumber>>,
mut exit: EventWriter<AppExit>,
) {
if events.len() > 0 {
println!(
"Funny number found: {:?}",
events.read().next().unwrap().0 .0
);
exit.send(AppExit::Success);
}
}