use std::error::Error;
use std::time::Duration;
use task_supervisor::{SupervisedTask, SupervisorBuilder, TaskError};
#[derive(Clone)]
struct MyTask {
pub emoji: char,
}
impl SupervisedTask for MyTask {
async fn run(&mut self) -> Result<(), TaskError> {
for _ in 0..15 {
println!("{} Task is running!", self.emoji);
tokio::time::sleep(Duration::from_secs(1)).await;
}
println!("{} Task completed!", self.emoji);
Ok(())
}
}
#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
let supervisor = SupervisorBuilder::default().build();
let handle = supervisor.run();
let h = handle.clone();
tokio::spawn(async move {
tokio::time::sleep(Duration::from_secs(5)).await;
println!("Adding a task after 5 seconds...");
h.add_task("task1", MyTask { emoji: '🆕' })
.expect("Failed to add task");
tokio::time::sleep(Duration::from_secs(2)).await;
match h.get_task_status("task1").await {
Ok(Some(status)) => println!("Task 'task1' status: {status:?}"),
Ok(None) => println!("Task 'task1' not found"),
Err(e) => println!("Error getting task status: {e}"),
}
tokio::time::sleep(Duration::from_secs(5)).await;
println!("Restarting task after 5 seconds...");
h.restart("task1").expect("Failed to restart task");
tokio::time::sleep(Duration::from_secs(2)).await;
match h.get_all_task_statuses().await {
Ok(statuses) => {
println!("All task statuses:");
for (name, status) in statuses {
println!(" {name}: {status:?}");
}
}
Err(e) => println!("Error getting all task statuses: {e}"),
}
tokio::time::sleep(Duration::from_secs(5)).await;
println!("Killing task after 5 seconds...");
h.kill_task("task1").expect("Failed to kill task");
tokio::time::sleep(Duration::from_secs(2)).await;
match h.get_task_status("task1").await {
Ok(Some(status)) => println!("Task 'task1' status after kill: {status:?}"),
Ok(None) => println!("Task 'task1' not found after kill"),
Err(e) => println!("Error getting task status after kill: {e}"),
}
tokio::time::sleep(Duration::from_secs(5)).await;
println!("Shutting down supervisor...");
h.shutdown().expect("Failed to shutdown supervisor");
});
handle.wait().await?;
println!("All tasks died and supervisor shut down!");
Ok(())
}