Struct SupervisorHandle

Source
pub struct SupervisorHandle { /* private fields */ }
Expand description

Handle used to interact with the Supervisor.

Implementations§

Source§

impl SupervisorHandle

Source

pub async fn wait(&self) -> Result<(), SupervisorError>

Waits for the supervisor to complete its execution.

§Returns
  • Ok(()) if the supervisor completed successfully.
  • Err(SupervisorError) if the supervisor returned an error.
Examples found in repository?
examples/simple.rs (line 88)
25async fn main() -> Result<(), Box<dyn Error>> {
26    // Build the supervisor with no initial tasks
27    let supervisor = SupervisorBuilder::default().build();
28
29    // Run the supervisor and get the handle
30    let handle = supervisor.run();
31
32    // Clone the handle for use in a separate task
33    let h = handle.clone();
34
35    // Spawn a task to manage and monitor the supervisor
36    tokio::spawn(async move {
37        // Add a new task after 5 seconds
38        tokio::time::sleep(Duration::from_secs(5)).await;
39        println!("Adding a task after 5 seconds...");
40        h.add_task("task1", MyTask { emoji: '🆕' })
41            .expect("Failed to add task");
42
43        // Check the status of the task after 2 seconds
44        tokio::time::sleep(Duration::from_secs(2)).await;
45        match h.get_task_status("task1").await {
46            Ok(Some(status)) => println!("Task 'task1' status: {status:?}"),
47            Ok(None) => println!("Task 'task1' not found"),
48            Err(e) => println!("Error getting task status: {e}"),
49        }
50
51        // Restart the task after 5 seconds
52        tokio::time::sleep(Duration::from_secs(5)).await;
53        println!("Restarting task after 5 seconds...");
54        h.restart("task1").expect("Failed to restart task");
55
56        // Check all task statuses after 2 seconds
57        tokio::time::sleep(Duration::from_secs(2)).await;
58        match h.get_all_task_statuses().await {
59            Ok(statuses) => {
60                println!("All task statuses:");
61                for (name, status) in statuses {
62                    println!("  {name}: {status:?}");
63                }
64            }
65            Err(e) => println!("Error getting all task statuses: {}", e),
66        }
67
68        // Kill the task after 5 seconds
69        tokio::time::sleep(Duration::from_secs(5)).await;
70        println!("Killing task after 5 seconds...");
71        h.kill_task("task1").expect("Failed to kill task");
72
73        // Check the status again after killing
74        tokio::time::sleep(Duration::from_secs(2)).await;
75        match h.get_task_status("task1").await {
76            Ok(Some(status)) => println!("Task 'task1' status after kill: {:?}", status),
77            Ok(None) => println!("Task 'task1' not found after kill"),
78            Err(e) => println!("Error getting task status after kill: {}", e),
79        }
80
81        // Shutdown the supervisor after 5 seconds
82        tokio::time::sleep(Duration::from_secs(5)).await;
83        println!("Shutting down supervisor...");
84        h.shutdown().expect("Failed to shutdown supervisor");
85    });
86
87    // Wait for the supervisor to complete
88    handle.wait().await?;
89    println!("All tasks died and supervisor shut down! 🫡");
90
91    Ok(())
92}
Source

pub fn add_task<T: CloneableSupervisedTask + 'static>( &self, task_name: &str, task: T, ) -> Result<(), SupervisorHandleError>

Adds a new task to the supervisor.

This method sends a message to the supervisor to add a new task with the specified name.

§Arguments
  • task_name: The unique name of the task.
  • task: The task to be added, which must implement SupervisedTask.
§Returns
  • Ok(()) if the message was sent successfully.
  • Err(SendError) if the supervisor is no longer running.
Examples found in repository?
examples/simple.rs (line 40)
25async fn main() -> Result<(), Box<dyn Error>> {
26    // Build the supervisor with no initial tasks
27    let supervisor = SupervisorBuilder::default().build();
28
29    // Run the supervisor and get the handle
30    let handle = supervisor.run();
31
32    // Clone the handle for use in a separate task
33    let h = handle.clone();
34
35    // Spawn a task to manage and monitor the supervisor
36    tokio::spawn(async move {
37        // Add a new task after 5 seconds
38        tokio::time::sleep(Duration::from_secs(5)).await;
39        println!("Adding a task after 5 seconds...");
40        h.add_task("task1", MyTask { emoji: '🆕' })
41            .expect("Failed to add task");
42
43        // Check the status of the task after 2 seconds
44        tokio::time::sleep(Duration::from_secs(2)).await;
45        match h.get_task_status("task1").await {
46            Ok(Some(status)) => println!("Task 'task1' status: {status:?}"),
47            Ok(None) => println!("Task 'task1' not found"),
48            Err(e) => println!("Error getting task status: {e}"),
49        }
50
51        // Restart the task after 5 seconds
52        tokio::time::sleep(Duration::from_secs(5)).await;
53        println!("Restarting task after 5 seconds...");
54        h.restart("task1").expect("Failed to restart task");
55
56        // Check all task statuses after 2 seconds
57        tokio::time::sleep(Duration::from_secs(2)).await;
58        match h.get_all_task_statuses().await {
59            Ok(statuses) => {
60                println!("All task statuses:");
61                for (name, status) in statuses {
62                    println!("  {name}: {status:?}");
63                }
64            }
65            Err(e) => println!("Error getting all task statuses: {}", e),
66        }
67
68        // Kill the task after 5 seconds
69        tokio::time::sleep(Duration::from_secs(5)).await;
70        println!("Killing task after 5 seconds...");
71        h.kill_task("task1").expect("Failed to kill task");
72
73        // Check the status again after killing
74        tokio::time::sleep(Duration::from_secs(2)).await;
75        match h.get_task_status("task1").await {
76            Ok(Some(status)) => println!("Task 'task1' status after kill: {:?}", status),
77            Ok(None) => println!("Task 'task1' not found after kill"),
78            Err(e) => println!("Error getting task status after kill: {}", e),
79        }
80
81        // Shutdown the supervisor after 5 seconds
82        tokio::time::sleep(Duration::from_secs(5)).await;
83        println!("Shutting down supervisor...");
84        h.shutdown().expect("Failed to shutdown supervisor");
85    });
86
87    // Wait for the supervisor to complete
88    handle.wait().await?;
89    println!("All tasks died and supervisor shut down! 🫡");
90
91    Ok(())
92}
Source

pub fn restart(&self, task_name: &str) -> Result<(), SupervisorHandleError>

Requests the supervisor to restart a specific task.

This method sends a message to the supervisor to restart the task with the given name.

§Arguments
  • task_name: The name of the task to restart.
§Returns
  • Ok(()) if the message was sent successfully.
  • Err(SendError) if the supervisor is no longer running.
Examples found in repository?
examples/simple.rs (line 54)
25async fn main() -> Result<(), Box<dyn Error>> {
26    // Build the supervisor with no initial tasks
27    let supervisor = SupervisorBuilder::default().build();
28
29    // Run the supervisor and get the handle
30    let handle = supervisor.run();
31
32    // Clone the handle for use in a separate task
33    let h = handle.clone();
34
35    // Spawn a task to manage and monitor the supervisor
36    tokio::spawn(async move {
37        // Add a new task after 5 seconds
38        tokio::time::sleep(Duration::from_secs(5)).await;
39        println!("Adding a task after 5 seconds...");
40        h.add_task("task1", MyTask { emoji: '🆕' })
41            .expect("Failed to add task");
42
43        // Check the status of the task after 2 seconds
44        tokio::time::sleep(Duration::from_secs(2)).await;
45        match h.get_task_status("task1").await {
46            Ok(Some(status)) => println!("Task 'task1' status: {status:?}"),
47            Ok(None) => println!("Task 'task1' not found"),
48            Err(e) => println!("Error getting task status: {e}"),
49        }
50
51        // Restart the task after 5 seconds
52        tokio::time::sleep(Duration::from_secs(5)).await;
53        println!("Restarting task after 5 seconds...");
54        h.restart("task1").expect("Failed to restart task");
55
56        // Check all task statuses after 2 seconds
57        tokio::time::sleep(Duration::from_secs(2)).await;
58        match h.get_all_task_statuses().await {
59            Ok(statuses) => {
60                println!("All task statuses:");
61                for (name, status) in statuses {
62                    println!("  {name}: {status:?}");
63                }
64            }
65            Err(e) => println!("Error getting all task statuses: {}", e),
66        }
67
68        // Kill the task after 5 seconds
69        tokio::time::sleep(Duration::from_secs(5)).await;
70        println!("Killing task after 5 seconds...");
71        h.kill_task("task1").expect("Failed to kill task");
72
73        // Check the status again after killing
74        tokio::time::sleep(Duration::from_secs(2)).await;
75        match h.get_task_status("task1").await {
76            Ok(Some(status)) => println!("Task 'task1' status after kill: {:?}", status),
77            Ok(None) => println!("Task 'task1' not found after kill"),
78            Err(e) => println!("Error getting task status after kill: {}", e),
79        }
80
81        // Shutdown the supervisor after 5 seconds
82        tokio::time::sleep(Duration::from_secs(5)).await;
83        println!("Shutting down supervisor...");
84        h.shutdown().expect("Failed to shutdown supervisor");
85    });
86
87    // Wait for the supervisor to complete
88    handle.wait().await?;
89    println!("All tasks died and supervisor shut down! 🫡");
90
91    Ok(())
92}
Source

pub fn kill_task(&self, task_name: &str) -> Result<(), SupervisorHandleError>

Requests the supervisor to kill a specific task.

This method sends a message to the supervisor to terminate the task with the given name.

§Arguments
  • task_name: The name of the task to kill.
§Returns
  • Ok(()) if the message was sent successfully.
  • Err(SendError) if the supervisor is no longer running.
Examples found in repository?
examples/simple.rs (line 71)
25async fn main() -> Result<(), Box<dyn Error>> {
26    // Build the supervisor with no initial tasks
27    let supervisor = SupervisorBuilder::default().build();
28
29    // Run the supervisor and get the handle
30    let handle = supervisor.run();
31
32    // Clone the handle for use in a separate task
33    let h = handle.clone();
34
35    // Spawn a task to manage and monitor the supervisor
36    tokio::spawn(async move {
37        // Add a new task after 5 seconds
38        tokio::time::sleep(Duration::from_secs(5)).await;
39        println!("Adding a task after 5 seconds...");
40        h.add_task("task1", MyTask { emoji: '🆕' })
41            .expect("Failed to add task");
42
43        // Check the status of the task after 2 seconds
44        tokio::time::sleep(Duration::from_secs(2)).await;
45        match h.get_task_status("task1").await {
46            Ok(Some(status)) => println!("Task 'task1' status: {status:?}"),
47            Ok(None) => println!("Task 'task1' not found"),
48            Err(e) => println!("Error getting task status: {e}"),
49        }
50
51        // Restart the task after 5 seconds
52        tokio::time::sleep(Duration::from_secs(5)).await;
53        println!("Restarting task after 5 seconds...");
54        h.restart("task1").expect("Failed to restart task");
55
56        // Check all task statuses after 2 seconds
57        tokio::time::sleep(Duration::from_secs(2)).await;
58        match h.get_all_task_statuses().await {
59            Ok(statuses) => {
60                println!("All task statuses:");
61                for (name, status) in statuses {
62                    println!("  {name}: {status:?}");
63                }
64            }
65            Err(e) => println!("Error getting all task statuses: {}", e),
66        }
67
68        // Kill the task after 5 seconds
69        tokio::time::sleep(Duration::from_secs(5)).await;
70        println!("Killing task after 5 seconds...");
71        h.kill_task("task1").expect("Failed to kill task");
72
73        // Check the status again after killing
74        tokio::time::sleep(Duration::from_secs(2)).await;
75        match h.get_task_status("task1").await {
76            Ok(Some(status)) => println!("Task 'task1' status after kill: {:?}", status),
77            Ok(None) => println!("Task 'task1' not found after kill"),
78            Err(e) => println!("Error getting task status after kill: {}", e),
79        }
80
81        // Shutdown the supervisor after 5 seconds
82        tokio::time::sleep(Duration::from_secs(5)).await;
83        println!("Shutting down supervisor...");
84        h.shutdown().expect("Failed to shutdown supervisor");
85    });
86
87    // Wait for the supervisor to complete
88    handle.wait().await?;
89    println!("All tasks died and supervisor shut down! 🫡");
90
91    Ok(())
92}
Source

pub fn shutdown(&self) -> Result<(), SupervisorHandleError>

Requests the supervisor to shut down all tasks and stop supervision.

This method sends a message to the supervisor to terminate all tasks and cease operation.

§Returns
  • Ok(()) if the message was sent successfully.
  • Err(SendError) if the supervisor is no longer running.
Examples found in repository?
examples/simple.rs (line 84)
25async fn main() -> Result<(), Box<dyn Error>> {
26    // Build the supervisor with no initial tasks
27    let supervisor = SupervisorBuilder::default().build();
28
29    // Run the supervisor and get the handle
30    let handle = supervisor.run();
31
32    // Clone the handle for use in a separate task
33    let h = handle.clone();
34
35    // Spawn a task to manage and monitor the supervisor
36    tokio::spawn(async move {
37        // Add a new task after 5 seconds
38        tokio::time::sleep(Duration::from_secs(5)).await;
39        println!("Adding a task after 5 seconds...");
40        h.add_task("task1", MyTask { emoji: '🆕' })
41            .expect("Failed to add task");
42
43        // Check the status of the task after 2 seconds
44        tokio::time::sleep(Duration::from_secs(2)).await;
45        match h.get_task_status("task1").await {
46            Ok(Some(status)) => println!("Task 'task1' status: {status:?}"),
47            Ok(None) => println!("Task 'task1' not found"),
48            Err(e) => println!("Error getting task status: {e}"),
49        }
50
51        // Restart the task after 5 seconds
52        tokio::time::sleep(Duration::from_secs(5)).await;
53        println!("Restarting task after 5 seconds...");
54        h.restart("task1").expect("Failed to restart task");
55
56        // Check all task statuses after 2 seconds
57        tokio::time::sleep(Duration::from_secs(2)).await;
58        match h.get_all_task_statuses().await {
59            Ok(statuses) => {
60                println!("All task statuses:");
61                for (name, status) in statuses {
62                    println!("  {name}: {status:?}");
63                }
64            }
65            Err(e) => println!("Error getting all task statuses: {}", e),
66        }
67
68        // Kill the task after 5 seconds
69        tokio::time::sleep(Duration::from_secs(5)).await;
70        println!("Killing task after 5 seconds...");
71        h.kill_task("task1").expect("Failed to kill task");
72
73        // Check the status again after killing
74        tokio::time::sleep(Duration::from_secs(2)).await;
75        match h.get_task_status("task1").await {
76            Ok(Some(status)) => println!("Task 'task1' status after kill: {:?}", status),
77            Ok(None) => println!("Task 'task1' not found after kill"),
78            Err(e) => println!("Error getting task status after kill: {}", e),
79        }
80
81        // Shutdown the supervisor after 5 seconds
82        tokio::time::sleep(Duration::from_secs(5)).await;
83        println!("Shutting down supervisor...");
84        h.shutdown().expect("Failed to shutdown supervisor");
85    });
86
87    // Wait for the supervisor to complete
88    handle.wait().await?;
89    println!("All tasks died and supervisor shut down! 🫡");
90
91    Ok(())
92}
Source

pub async fn get_task_status( &self, task_name: &str, ) -> Result<Option<TaskStatus>, SupervisorHandleError>

Queries the status of a specific task asynchronously.

This method sends a request to the supervisor to retrieve the status of the specified task and awaits the response.

§Arguments
  • task_name: The name of the task to query.
§Returns
  • Ok(Some(TaskStatus)) if the task exists and its status is returned.
  • Ok(None) if the task does not exist.
  • Err(RecvError) if communication with the supervisor fails (e.g., it has shut down).
Examples found in repository?
examples/simple.rs (line 45)
25async fn main() -> Result<(), Box<dyn Error>> {
26    // Build the supervisor with no initial tasks
27    let supervisor = SupervisorBuilder::default().build();
28
29    // Run the supervisor and get the handle
30    let handle = supervisor.run();
31
32    // Clone the handle for use in a separate task
33    let h = handle.clone();
34
35    // Spawn a task to manage and monitor the supervisor
36    tokio::spawn(async move {
37        // Add a new task after 5 seconds
38        tokio::time::sleep(Duration::from_secs(5)).await;
39        println!("Adding a task after 5 seconds...");
40        h.add_task("task1", MyTask { emoji: '🆕' })
41            .expect("Failed to add task");
42
43        // Check the status of the task after 2 seconds
44        tokio::time::sleep(Duration::from_secs(2)).await;
45        match h.get_task_status("task1").await {
46            Ok(Some(status)) => println!("Task 'task1' status: {status:?}"),
47            Ok(None) => println!("Task 'task1' not found"),
48            Err(e) => println!("Error getting task status: {e}"),
49        }
50
51        // Restart the task after 5 seconds
52        tokio::time::sleep(Duration::from_secs(5)).await;
53        println!("Restarting task after 5 seconds...");
54        h.restart("task1").expect("Failed to restart task");
55
56        // Check all task statuses after 2 seconds
57        tokio::time::sleep(Duration::from_secs(2)).await;
58        match h.get_all_task_statuses().await {
59            Ok(statuses) => {
60                println!("All task statuses:");
61                for (name, status) in statuses {
62                    println!("  {name}: {status:?}");
63                }
64            }
65            Err(e) => println!("Error getting all task statuses: {}", e),
66        }
67
68        // Kill the task after 5 seconds
69        tokio::time::sleep(Duration::from_secs(5)).await;
70        println!("Killing task after 5 seconds...");
71        h.kill_task("task1").expect("Failed to kill task");
72
73        // Check the status again after killing
74        tokio::time::sleep(Duration::from_secs(2)).await;
75        match h.get_task_status("task1").await {
76            Ok(Some(status)) => println!("Task 'task1' status after kill: {:?}", status),
77            Ok(None) => println!("Task 'task1' not found after kill"),
78            Err(e) => println!("Error getting task status after kill: {}", e),
79        }
80
81        // Shutdown the supervisor after 5 seconds
82        tokio::time::sleep(Duration::from_secs(5)).await;
83        println!("Shutting down supervisor...");
84        h.shutdown().expect("Failed to shutdown supervisor");
85    });
86
87    // Wait for the supervisor to complete
88    handle.wait().await?;
89    println!("All tasks died and supervisor shut down! 🫡");
90
91    Ok(())
92}
Source

pub async fn get_all_task_statuses( &self, ) -> Result<HashMap<String, TaskStatus>, SupervisorHandleError>

Queries the statuses of all tasks asynchronously.

This method sends a request to the supervisor to retrieve the statuses of all tasks and awaits the response.

§Returns
  • Ok(HashMap<TaskName, TaskStatus>) containing the statuses of all tasks.
  • Err(RecvError) if communication with the supervisor fails (e.g., it has shut down).
Examples found in repository?
examples/simple.rs (line 58)
25async fn main() -> Result<(), Box<dyn Error>> {
26    // Build the supervisor with no initial tasks
27    let supervisor = SupervisorBuilder::default().build();
28
29    // Run the supervisor and get the handle
30    let handle = supervisor.run();
31
32    // Clone the handle for use in a separate task
33    let h = handle.clone();
34
35    // Spawn a task to manage and monitor the supervisor
36    tokio::spawn(async move {
37        // Add a new task after 5 seconds
38        tokio::time::sleep(Duration::from_secs(5)).await;
39        println!("Adding a task after 5 seconds...");
40        h.add_task("task1", MyTask { emoji: '🆕' })
41            .expect("Failed to add task");
42
43        // Check the status of the task after 2 seconds
44        tokio::time::sleep(Duration::from_secs(2)).await;
45        match h.get_task_status("task1").await {
46            Ok(Some(status)) => println!("Task 'task1' status: {status:?}"),
47            Ok(None) => println!("Task 'task1' not found"),
48            Err(e) => println!("Error getting task status: {e}"),
49        }
50
51        // Restart the task after 5 seconds
52        tokio::time::sleep(Duration::from_secs(5)).await;
53        println!("Restarting task after 5 seconds...");
54        h.restart("task1").expect("Failed to restart task");
55
56        // Check all task statuses after 2 seconds
57        tokio::time::sleep(Duration::from_secs(2)).await;
58        match h.get_all_task_statuses().await {
59            Ok(statuses) => {
60                println!("All task statuses:");
61                for (name, status) in statuses {
62                    println!("  {name}: {status:?}");
63                }
64            }
65            Err(e) => println!("Error getting all task statuses: {}", e),
66        }
67
68        // Kill the task after 5 seconds
69        tokio::time::sleep(Duration::from_secs(5)).await;
70        println!("Killing task after 5 seconds...");
71        h.kill_task("task1").expect("Failed to kill task");
72
73        // Check the status again after killing
74        tokio::time::sleep(Duration::from_secs(2)).await;
75        match h.get_task_status("task1").await {
76            Ok(Some(status)) => println!("Task 'task1' status after kill: {:?}", status),
77            Ok(None) => println!("Task 'task1' not found after kill"),
78            Err(e) => println!("Error getting task status after kill: {}", e),
79        }
80
81        // Shutdown the supervisor after 5 seconds
82        tokio::time::sleep(Duration::from_secs(5)).await;
83        println!("Shutting down supervisor...");
84        h.shutdown().expect("Failed to shutdown supervisor");
85    });
86
87    // Wait for the supervisor to complete
88    handle.wait().await?;
89    println!("All tasks died and supervisor shut down! 🫡");
90
91    Ok(())
92}

Trait Implementations§

Source§

impl Clone for SupervisorHandle

Source§

fn clone(&self) -> SupervisorHandle

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for SupervisorHandle

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Drop for SupervisorHandle

Source§

fn drop(&mut self)

Automatically shuts down the supervisor when the handle is dropped.

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.