AnyEvent timer question
Asked Answered
T

2

5

How could I make "visible" the timer? This example returns (intependent from the sleep-time always) 2 (I expected something similar to the sleep-time).

#!/usr/local/bin/perl
use warnings;
use 5.014;
use AnyEvent;

my $c = 0;
my $cv = AnyEvent->condvar;

my $once_per_second = AnyEvent->timer (
    after => 0,
    interval => 1,
    cb => sub {
        $c++;
        $cv->send;
    },
);

sleep 5;

$cv->recv;

say $c;
Tassel answered 28/7, 2011 at 6:40 Comment(0)
P
6

There are at least two problems:

  • sleep 5 doesn't run the event loop.
  • Your callback triggers the cond. variable. If, for instance, you removed the sleep 5 statement, $c would only be 1.

Is this what you want?

my $c = 0;
my $cv = AnyEvent->condvar;
my $once_per_second = AnyEvent->timer(after => 0, interval => 1, cb => sub { $c++ });
my $five_seconds = AnyEvent->timer(after => 5, cb => sub { $cv->send });
$cv->recv;
say $c;
Pejoration answered 28/7, 2011 at 7:18 Comment(2)
I did not yet understand why with sleep I get 2 instead of 1.Tassel
You are getting one callback for the "after => 0" and then one callback for the first interval. Try creating the timer without specifying the "after" and see if $c is 1.Pejoration
J
3

The event loop is not running (well nothing is running) while sleep is "active". So no event registered with AnyEvent can be triggered.

The rule: If you use AnyEvent (or any other ansynchronous framework), never use sleep.

See user5402's answer for the correct solution.

Judy answered 4/9, 2012 at 16:1 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.