Skip to content

Instantly share code, notes, and snippets.

@saillinux
Created January 20, 2011 09:47
Show Gist options
  • Save saillinux/787660 to your computer and use it in GitHub Desktop.
Save saillinux/787660 to your computer and use it in GitHub Desktop.
anyevent more proper port checking with given interval.
#!/usr/bin/env perl
use strict;
use warnings;
use AnyEvent::Socket;
use constant INTERVAL => 1;
use constant COOLTIME => 300;
my ($host, $port) = @ARGV;
die "No host name is given" unless defined $host;
die "No port numb is given" unless defined $port;
my $cv = AnyEvent->condvar;
my $once_per_second;
$once_per_second = AnyEvent->timer(interval => INTERVAL,
cb => \&port_check,
);
$cv->wait;
sub port_check {
my $done = AnyEvent->condvar;
tcp_connect $host, $port, sub {
my ($fh) = @_ or do {
my $time = localtime;
warn "The host or service is down with [$!] at $time\n"; # print 'timeout' at most every second
undef $once_per_second;
$once_per_second = AnyEvent->timer(after => COOLTIME,
interval => INTERVAL,
cb => \&port_check,
);
return;
};
my $time = localtime;
warn "Host($host) is alive at $time";
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment