Time::Out - Easily timeout long running operations
use Time::Out ; timeout $nb_secs => affects { # your code goes were and will be interrupted if it runs # for more than $nb_secs seconds. } ; if ($@){ # operation timed-out }
Time::Out provides an easy interface to alarm(2) based timeouts.
Time::Out
Time::Out exports 2 symbols, 'timeout' and 'affects'. However, these should only be used according to the syntax shown above.
Note: If fact, the 'affects' is really just a no-op to hide the fact that the code is being placed inside another sub (I felt this fact might confuse folks who are Perl newbies). You could (and probably should) just as well say:
use Time::Out ; timeout $nb_secs => sub { # ... } ;
'timeout' returns whatever the code placed inside the block returns:
use Time::Out ; my $rc = timeout 5 => affects { return 7 ; } ; # $rc == 7
Time::HiRes
If Time::Out sees that Time::HiRes has been loaded, it will use that 'alarm' function (if available) instead of the default one, allowing float timeout values to be usedi effectively:
use Time::Out ; use Time::HiRes ; timeout 3.1416 => affects { # ... } ;
alarm(2) doesn't interrupt blocking I/O on MSWin32, so 'timeout' won't do that either.
One drawback to using 'timeout' is that it masks @_ in the affected code. This happens because the affected code is actually wrapped inside another subroutine that provides it's own @_. You can get around this by specifically passing your @_ (or whatever you want for that matter) to 'timeout' as such:
use Time::Out ; sub test { timeout 5, @_ => affects { print "$_[0]\n" ; } ; } test("hello") ; # will print "hello\n" ;
eval, closures, alarm(2)
Patrick LeBoutillier, <patl@cpan.org>
Copyright 2005 by Patrick LeBoutillier
This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
To install Time::Out, copy and paste the appropriate command in to your terminal.
cpanm
cpanm Time::Out
CPAN shell
perl -MCPAN -e shell install Time::Out
For more information on module installation, please visit the detailed CPAN module installation guide.