AnyEventについて調べる

AnyEvent->timer(
  after => $after,
  interval => $interval,
  cb => sub {
    ....
  }
);
AE::timer $after, $interval, sub {
  ...
};
  • タイマーウォッチャー
use strict;
use warnings;
use AnyEvent;

my $cv = AnyEvent->condvar;
my $count = 0;
my $timer; $timer = AE::timer 0, 1, sub {
    $count++;
    warn "timer [$count]   " . time();
    if ($count >= 9) {
        undef $timer;
        $cv->send;
    }
};
warn "timer start " . time();
$cv->recv;

timer start 1311954349 at timer.pl line 16.
timer [1]   1311954349 at timer.pl line 10.
timer [2]   1311954350 at timer.pl line 10.
timer [3]   1311954351 at timer.pl line 10.
timer [4]   1311954352 at timer.pl line 10.
timer [5]   1311954353 at timer.pl line 10.
timer [6]   1311954354 at timer.pl line 10.
timer [7]   1311954355 at timer.pl line 10.
timer [8]   1311954356 at timer.pl line 10.
timer [9]   1311954357 at timer.pl line 10.
use strict;
use warnings;
use AnyEvent;

open my $fh, "<", "$0";

my $cv = AE::cv;
my $io; $io = AE::io $fh, 0, sub {
    my $len = sysread($fh, my $buf, 1);
    if ($len > 0) {
        my $hex = unpack("C*", $buf);
        warn sprintf("read '0x%02x' $buf", $hex);
        sleep 1;
    } elsif (defined $len) {
        undef $io;
        close $fh;
        $cv->send;
    } else {
        undef $io;
        close $fh;
        $cv->send;
        die "err";
    }
};
$cv->recv;

read '0x75' u at io.pl line 12.
read '0x73' s at io.pl line 12.
read '0x65' e at io.pl line 12.
read '0x20'   at io.pl line 12.
read '0x73' s at io.pl line 12.
read '0x74' t at io.pl line 12.
read '0x72' r at io.pl line 12.
read '0x69' i at io.pl line 12.
read '0x63' c at io.pl line 12.
read '0x74' t at io.pl line 12.
read '0x3b' ; at io.pl line 12.
  • 特定の条件が満たされるまで待つ
use strict;
use warnings;
use File::Temp qw/ tempdir /;
use AnyEvent;

my $cv = AE::cv;
for my $i (1..10) {
    $cv->begin;
    my $w; $w = AE::timer $i, 0, sub {
        warn "finished timer $i";
        undef $w;
        $cv->end;
    };
}
$cv->recv;

finished timer 1 at m.pl line 11.
finished timer 2 at m.pl line 11.
finished timer 3 at m.pl line 11.
finished timer 4 at m.pl line 11.
finished timer 5 at m.pl line 11.
finished timer 6 at m.pl line 11.
finished timer 7 at m.pl line 11.
finished timer 8 at m.pl line 11.
finished timer 9 at m.pl line 11.
finished timer 10 at m.pl line 11.