chain_retries_delay_cleanup/
chain_retries_delay_cleanup.rs

1use std::time::Duration;
2
3use bevy::prelude::*;
4use bevy_local_commands::{
5    BevyLocalCommandsPlugin, Chain, Cleanup, Delay, LocalCommand, ProcessCompleted, ProcessOutput,
6    Retry,
7};
8
9fn main() {
10    App::new()
11        .add_plugins((MinimalPlugins, BevyLocalCommandsPlugin))
12        .add_systems(Startup, setup)
13        .add_systems(Update, update)
14        .run();
15}
16
17fn setup(mut commands: Commands) {
18    // Spawn a entity with all addons
19    #[cfg(not(windows))]
20    let chain = Chain::new(vec![
21        LocalCommand::new("sh").args(["-c", "echo 'First command'"]),
22        LocalCommand::new("sh").args(["-c", "echo 'Second command'"]),
23        LocalCommand::new("sh").args(["-c", "echo 'Third command'"]),
24    ]);
25    #[cfg(windows)]
26    let chain = Chain::new(vec![
27        LocalCommand::new("powershell").args(["echo 'First command'"]),
28        LocalCommand::new("powershell").args(["echo 'Second command'"]),
29        LocalCommand::new("powershell").args(["echo 'Third command'"]),
30    ]);
31    let id = commands
32        .spawn((
33            chain,
34            Retry::Attempts(2),
35            Delay::Fixed(Duration::from_secs(3)),
36            Cleanup::RemoveComponents,
37        ))
38        .id();
39    println!("Spawned as entity {id:?}");
40}
41
42fn update(
43    mut process_output_event: MessageReader<ProcessOutput>,
44    mut process_completed_event: MessageReader<ProcessCompleted>,
45    command_query: Query<(), (With<Chain>, With<Retry>, With<Delay>, With<Cleanup>)>,
46) {
47    for process_output in process_output_event.read() {
48        for line in process_output.lines() {
49            println!("Output Line ({:?}): {line}", process_output.entity);
50        }
51    }
52
53    for process_completed in process_completed_event.read() {
54        println!(
55            "Command {:?} completed (Success - {})",
56            process_completed.entity,
57            process_completed.exit_status.success()
58        );
59    }
60
61    // Check if our entity is done running chain commands
62    if command_query.is_empty() {
63        println!("All commands completed - cleanup performed. Exiting the app.");
64        std::process::exit(0);
65    }
66}