Search notes:

Perl function: alarm

#
#   Compare with alarm_2.pl
#
use warnings;
use strict;

use Time::HiRes 'time';

my $run = 1;

$SIG{ALRM} = sub {

   $run = 0;
   print "Timeout reached\n";

};

alarm 3;

my $start_time = time;

while ($run) {
  print time - $start_time, "\n";
}
Github repository about-perl, path: /functions/alarm.pl
#
# http://stackoverflow.com/a/28104243/180275
#
#   Compare with alarm.pl
#
use warnings;
use strict;
use Time::HiRes 'time';

$|=1;

for my $i (1 .. 10) {

  local $SIG{ALRM} = sub {
    die;
  };

  eval {
    alarm 5;
    sub_info($i);
  };

  if ($@) {
    print "aborted\n";
  }
  alarm 0;
}

sub sub_info {
  my $i = shift;
  my $r = int(10*rand);

  printf "Trying %2d for %2d seconds: ", $i, $r;

# Alternatively: "sleep $r" instead of the
# two following lines
  my $start_time = time;
  1 while time - $start_time < $r;

  print "finished\n";
}
Github repository about-perl, path: /functions/alarm_2.pl

See also

libc function alarm()
Perl functions

Index