| Crates.io | context-async |
| lib.rs | context-async |
| version | 1.0.0 |
| created_at | 2024-12-13 16:09:22.087968+00 |
| updated_at | 2024-12-24 19:43:56.423467+00 |
| description | context handle async future timeout or cancel |
| homepage | |
| repository | https://github.com/caojen/async-context |
| max_upload_size | |
| id | 1482317 |
| size | 117,964 |
This lib provide an trait Context and a Timer to control async function.
It's based on tokio.
Add this lib as dependencies in Cargo.toml.
[dependencies]
context-async = { version = "*" }
In your code, you can simple use Timer:
use std::time;
use context_async::{Context, Timer, Error, With};
async fn a_heavy_function_or_something_else(a: u8, b: u128) -> Result<(), ()>{
// ....
Ok(())
}
#[tokio::main]
async fn main() {
let timer = Timer::with_timeout(time::Duration::from_secs(3));
let fut = a_heavy_function_or_something_else(1, 1024);
let result = timer.handle(fut).await; // use `handle`
// or:
// let result = fut.with(timer).await; // trait `With`
let result = match result {
Err(err) => match err {
Error::ContextCancelled => "context cancelled",
Error::ContextTimeout => "context timeout",
},
Ok(Err(_)) => "async function error",
Ok(Ok(_)) => "async function ok",
};
}
Timer and Context implements Clone, which creates a new Context (same as itself).
Timer and Context can spawn children contexts, and ensure the following conditions are met:
for more information, see examples or visit the documentation.