sub check_database_health { my $db_host = shift; my %health; debug(4, "Checking connect time for $db_host"); my $dbh; my $connect_time; my $seconds = 2; my $mask = POSIX::SigSet->new( SIGALRM ); # signals to mask in the handler my $action = POSIX::SigAction->new( sub { die "connect timeout" }, # the handler code ref $mask, ); my $oldaction = POSIX::SigAction->new(); sigaction( &POSIX::SIGALRM, $action, $oldaction ); eval { alarm($seconds); my $start_time = time; $dbh = DBI->connect("DBI:mysql:database=test;host=$db_host", 'check_health', '******', { RaiseError => 1, PrintError => 0 }); or die "Could not connect to $db_host: " . $DBI::errstr; my $end_time = time; $connect_time = $end_time - $start_time; alarm 0; # cancel alarm (if code ran fast) }; sigaction( &POSIX::SIGALRM, $oldaction ); # restore original signal handler if ( $@ ) { debug(4, "Problem!: $@"); return undef; } else { $health{connect_time} = $connect_time; debug(4, "OK - $connect_time seconds"); } }