16.21. Timing Out an Operation

Problem

You want to make sure an operation doesn't take more than a certain amount of time. For instance, you're running filesystem backups and want to abort if it takes longer than an hour. Or, you want to schedule an event for the next hour.

Solution

To interrupt a long-running operation, set a SIGALRM handler to call die . Set an alarm with alarm , then eval your code:

$SIG{ALRM} = sub { die "timeout" };

eval {
    alarm(3600);
    # long-time operations here
    alarm(0);
};

if ($@) {
    if ($@ =~ /timeout/) {
                            # timed out; do what you will here
    } else {
        alarm(0);           # clear the still-pending alarm
        die;                # propagate unexpected exception
    } 
} 

Discussion

The alarm function takes one argument: the integer number of seconds before your process receives a SIGALRM. It may be delivered after that time in busy time-sharing systems. The default action for SIGALRM is to terminate your program, so you should install your own signal handler.

You cannot (usefully) give the alarm function a fractional number of seconds; if you try, it will be truncated to an integer. For precise timers, see Recipe 3.9 .

See Also

The "Signals" sections in Chapter 6 of Programming Perl and in perlipc (1); the alarm function in Chapter 3 of Programming Perl and in perlfunc (1); Recipe 3.9