Use tokio::time::timeout to wrap an async operation and enforce a maximum execution time.
use tokio::time::{timeout, Duration};
async fn fetch_data() -> Result<String, String> {
// Simulate async work
tokio::time::sleep(Duration::from_secs(5)).await;
Ok("data".to_string())
}
#[tokio::main]
async fn main() {
let result = timeout(Duration::from_secs(2), fetch_data()).await;
match result {
Ok(Ok(data)) => println!("Got data: {}", data),
Ok(Err(e)) => println!("Task failed: {}", e),
Err(_) => println!("Task timed out"),
}
}