bwnyasse
bwnyasse

Reputation: 629

How to timeout a future computation after a timeLimit?

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 ?

Upvotes: 27

Views: 26432

Answers (4)

Cyrax
Cyrax

Reputation: 827

In order to stop any Future by timeout one can use timeout(). There are two examples:

  1. Throw exception after timeout
  final someHardTaskFuture = Future.delayed(const Duration(hours: 1), () => 42);
  final newFutureWithTimeoutAndException = someHardTaskFuture.timeout(const Duration(seconds: 3));
  1. Returns default value (11) on timeout
  final someHardTaskFuture = Future.delayed(const Duration(hours: 1), () => 42);
  final newFutureWithTimeoutAndDefaultValue = someHardTaskFuture
      .timeout(const Duration(seconds: 3), onTimeout: () => 11);
  print(await newFutureWithTimeoutAndDefaultValue);

Upvotes: 0

Airon Tark
Airon Tark

Reputation: 9476

Using async/await style. You can add .timeout to any Future you are awaiting.

final result = await InternetAddress
   .lookup('example.com')
   .timeout(
      Duration(seconds: 10),
      onTimeout: () => throw TimeoutException('Can\'t connect in 10 seconds.'),
    );

Upvotes: 3

Nhật Trần
Nhật Trần

Reputation: 2828

Future.await[_doSome].then((data){
    print(data);
    }).timeout(Duration(seconds: 10));

Upvotes: 15

G&#252;nter Z&#246;chbauer
G&#252;nter Z&#246;chbauer

Reputation: 657158

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()

Upvotes: 21

Related Questions