Crate tokio_tasks
source ·Expand description
Task manager for tokio. Facilitates clean shutdow of applications, and async cancelation of tasks
§Example
use tokio_tasks::{TaskBuilder, run_tasks, shutdown, cancelable, RunToken};
// Main task, program will shut down if when finishes
async fn main_task(run_token: RunToken) -> Result<(), String> {
println!("Main task start");
match cancelable(&run_token, tokio::time::sleep(std::time::Duration::from_secs(10))).await {
Ok(()) => println!("Main task finished"),
Err(_) => println!("Main task cancled"),
}
Ok(())
}
// Critical task, program will shut down if this finished with an error
async fn critical_task(run_token: RunToken) -> Result<(), String> {
println!("Critical task start");
match cancelable(&run_token, tokio::time::sleep(std::time::Duration::from_secs(1))).await {
Ok(()) => println!("Critical task finished"),
Err(_) => println!("Critical task cancled"),
}
Ok(())
}
TaskBuilder::new("main_task")
.main()
.shutdown_order(1)
.create(|rt| main_task(rt));
TaskBuilder::new("critical_task")
.critical()
.shutdown_order(2)
.create(|rt| critical_task(rt));
// Normally one would register the program to stop on ctrl+c
// tokio::spawn(async {
// tokio::signal::ctrl_c().await.unwrap();
// shutdown("ctrl+c".to_string());
// });
// We just shut down after a little while
tokio::spawn(async {
tokio::time::sleep(std::time::Duration::from_millis(20)).await;
shutdown("timeout".to_string());
});
run_tasks().await;
Re-exports§
pub use task::FinishState;
Structs§
- Error returned by cancelable when c was canceled before the future returned
- Similar to a [
tokio_util::sync::CancellationToken
], the RunToken encapsulates the possibility of canceling an async command. However it also allows pausing and resuming the async command, and it is possible to wait in both a blocking fashion and an asynchronous fashion. - A possible running task, with a return value of
Result<T, E>
- Builder to create a new task
- Wait until task cancellation is completed
Enums§
- Error return while waiting for a task
Traits§
- Base trait for all tasks, that is independent of the return type
Functions§
- Return result from fut, unless run_token is canceled before fut is done
- Return a list of all currently running tasks
- Wait until all tasks are done or shutdown has been called
- Cancel all tasks in shutdown order
- Try to return a list of all currently running tasks, if we cannot acquire the lock for the tasks before duration has passed return None