Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to timeout a future computation after a timeLimit?

Tags:

dart

dart-html

When defining a Future as follows:

Future<HttpRequest> httpRequest =  HttpRequest.request(url,
      method: method, requestHeaders: requestHeaders);

I want to handle a timeout after 5 secondes. I'm writing my code like this :

httpRequest.timeout(const Duration (seconds:5),onTimeout : _onTimeout());

Where my timeout function is :

_onTimeout() => print("Time Out occurs");

According to the Future timeout() method documentation , If onTimeout is omitted, a timeout will cause the returned future to complete with a TimeoutException. But With my code , my method _onTimeout() is properly called (but immediately, not after 5 seconds) and I always get a

TimeException after 5 seconds... (TimeoutException after 0:00:05.000000: Future not completed )

Am I missing something ?

like image 840
bwnyasse Avatar asked Nov 24 '15 15:11

bwnyasse


People also ask

How do you stop a function if it takes too long python?

So, in your application code, you can use the decorator like so: from timeout import timeout # Timeout a long running function with the default expiry of 10 seconds. @timeout def long_running_function1(): ... # Timeout after 5 seconds @timeout(5) def long_running_function2(): ...

How do you use the future in darts?

A future (lower case “f”) is an instance of the Future (capitalized “F”) class. A future represents the result of an asynchronous operation, and can have two states: uncompleted or completed. Note: Uncompleted is a Dart term referring to the state of a future before it has produced a value.


2 Answers

Change this line

httpRequest.timeout(const Duration (seconds:5),onTimeout : _onTimeout());

to

httpRequest.timeout(const Duration (seconds:5),onTimeout : () => _onTimeout());

or just pass a reference to the function (without the ())

httpRequest.timeout(const Duration (seconds:5),onTimeout : _onTimeout);

This way the closure that calls _onTimeout() will be passed to timeout(). In the former code the result of the _onTimeout() call will be passed to timeout()

like image 200
Günter Zöchbauer Avatar answered Sep 28 '22 00:09

Günter Zöchbauer


Future.await[_doSome].then((data){
    print(data);
    }).timeout(Duration(seconds: 10));
like image 29
Nhật Trần Avatar answered Sep 27 '22 23:09

Nhật Trần