I've got a bunch of classes that do different operations over the network, and as we all know, network operations sometimes time-out. So I'm thinking of doing something like this:
package My::Role::NetworkFetcher {
use Moose::Role;
sub BUILD {
my $self = shift;
local $SIG{ALRM} = sub {
$self->handle_timeout;
};
alarm 60;
}
sub handle_timeout {
die "default timeout handler";
}
}
I'm not sure if this is the best way to go about this. It seems to work OK in my very simple test cases, but I'm not sure if hijacking the object's BUILD
method or localizing a signal handler in this way is correct or even advisable.
Careful here. The local $SIG{ALRM} only applies to the BUILD method, so if you leave the scope of the function without making a call to alarm 0, then the default ALRM handler will happen if you left the BUILD method and the timeout occurs. It is safest to do the entire thing within an eval so you don't run into obscure problems.