I'm trying to get some piece of code to run for at most timeout
duration. In other words I want a piece of code to either complete in the given time constraint or be interrupted.
The concrete code that would be running would be a multi-part http request which i want to terminate if the request is not completed in a time-frame. I have tried the Timeou
from the tokio-timer
crate but i am having some issues.
use futures::future;
use std::time::Duration;
use tokio::io::Error;
use tokio::prelude::*;
use tokio::runtime::current_thread::Runtime;
fn main() {
let timeout: u64 = 1000;
let mut runtime = Runtime::new().unwrap();
let req_timeout = future::lazy(|| -> Result<String, Error> {
println!("Start expensive");
loop {
//some expensive task
}
Ok("finished task".to_string())
})
.timeout(Duration::from_millis(timeout));
let result = runtime.block_on(req_timeout);
match result {
Ok(_str) => println!("Task finished"),
Err(_) => println!("Task interupted"),
}
}
Currently the timeout never triggers leaving the loop
to execute forever instead of being interrupted and resuming the execution from the block_on
call. I'm sure, I am missing something, but I can't really figure it out.