5

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.

Stargateur
  • 24,473
  • 8
  • 65
  • 91
vuk
  • 91
  • 8
  • Cross github [issue](https://github.com/tokio-rs/tokio/issues/1035) – Stargateur Apr 04 '19 at 13:13
  • @Stargateur yeah that's me – vuk Apr 04 '19 at 13:19
  • Cross question/issue are completely ok, I just make them linked, to avoid waste time if any side have the answer first. – Stargateur Apr 04 '19 at 13:32
  • What you have is a timer future that wraps an infinite loop. Tokio then calls and waits for [timer's poll function](https://github.com/tokio-rs/tokio/blob/tokio-timer-0.2.10/tokio-timer/src/timeout.rs#L201) which in turn [calls and waits](https://github.com/tokio-rs/tokio/blob/tokio-timer-0.2.10/tokio-timer/src/timeout.rs#L203) for your infinite loop. – so61pi Apr 04 '19 at 15:10

0 Answers0