http://www.perlmonks.org?node_id=995486


in reply to Help with timeout

G'day eversuhoshin,

"I have looked up Alarm but I don't know how to incorporate it into my code."

Using the same code structure given in the alarm example, here's how you might do this:

#!/usr/bin/env perl use strict; use warnings; my @iterations = map { 10 ** $_ } 0 .. 10; my $timeout = 2; for my $iterations_this_loop (@iterations) { eval { local $SIG{ALRM} = sub { die "TIMEOUT: $iterations_this_loop\n +" }; alarm $timeout; for (0 .. $iterations_this_loop) { # Processing here } alarm 0; }; if ($@) { die $@ unless $@ =~ /^TIMEOUT: \d+/; # propagate unexpected +errors print $@; next; } else { print "ENOUGH TIME: $iterations_this_loop\n"; } }

Output:

$ pm_long_for_alarm.pl ENOUGH TIME: 1 ENOUGH TIME: 10 ENOUGH TIME: 100 ENOUGH TIME: 1000 ENOUGH TIME: 10000 ENOUGH TIME: 100000 ENOUGH TIME: 1000000 ENOUGH TIME: 10000000 TIMEOUT: 100000000 TIMEOUT: 1000000000 TIMEOUT: 10000000000

for my $iterations_this_loop (@iterations) { represents the number of records in each file (that will be foreach (@files){ in your code).

for (0 .. $iterations_this_loop) { represents processing that number of records (that will be the processing you are doing within each iteration of your loop).

Note: the argument to alarm is in seconds - for 2 minutes you'll need my $timeout = 120;.

-- Ken