2013/12/21

Futures advent day 21

Day 21 - Implementing Timeouts

Suppose now we have a function called TIMEOUT(), similar to SLEEP() except it returns a future that will fail at some later time. We can combine this with another future using the wait_any combination function, to create a timeout. Like needs_any and needs_all, this combination function takes a list of futures and returns a future representing their combination. In this case the combination will complete as soon as any of the individual futures completes, regardless of success or failure. At this point, any other pending futures are cancelled.

my $f = Future->wait_any(
  GET( "http://my-site-here.com/might-be-slow" ),
  TIMEOUT( 20 ),
);

my $page = $f->get;

Here we are using wait_any to add timeout behaviour to a page get operation. If the HTTP operation either succeeds or fails before the 20 seconds are up then $f will complete with the same result or failure, and the timeout will be cancelled. Alternatively, if it still has no result after 20 seconds then the timeout future will fail, causing the overall future $f to fail, and the HTTP operation will be cancelled. In this way we can easily add timeout behaviour to any future-returning function, without every operation individually having to implement timeouts of any kind.

<< First | < Prev | Next >

No comments:

Post a Comment

Post a Comment