Subject: | ->stop doesn't when called from on_tick callback |
The following "run N times" idiom doesn't quite work as expected, since ->start is called immediately after the on_tick callback:
#!/usr/bin/env perl
use strict;
use warnings;
use IO::Async::Loop;
use IO::Async::Timer::Periodic;
use Future;
my $loop = IO::Async::Loop->new;
my $f = Future->new;
my $count = 0;
my $t = IO::Async::Timer::Periodic->new(
interval => 0.1,
on_tick => sub {
$f->done if ++$count > 5 && !$f->is_ready;
warn "exceeded 5 iterations" if $count > 6;
}
);
$loop->add($t);
$t->start;
$f->on_done(sub { warn "Stopping timer"; $t->stop });
$loop->run;
__END__
Stopping timer at timer.pl line 20.
exceeded 5 iterations at timer.pl line 15.
exceeded 5 iterations at timer.pl line 15.
exceeded 5 iterations at timer.pl line 15.
exceeded 5 iterations at timer.pl line 15.
...
One workaround would be to set a flag when this happens (patch attached), only affects ::Periodic as far as I can see.
cheers,
Tom
Subject: | periodic-timer-stop.diff |
=== modified file 'lib/IO/Async/Timer.pm'
--- lib/IO/Async/Timer.pm 2013-04-05 18:24:12 +0000
+++ lib/IO/Async/Timer.pm 2013-04-10 17:49:16 +0000
@@ -167,6 +167,7 @@
return;
}
+ $self->{please_stop} = 1;
return if !$self->is_running;
my $loop = $self->loop or croak "Cannot stop a Timer that is not in a Loop";
=== modified file 'lib/IO/Async/Timer/Periodic.pm'
--- lib/IO/Async/Timer/Periodic.pm 2013-04-05 18:24:12 +0000
+++ lib/IO/Async/Timer/Periodic.pm 2013-04-10 17:49:36 +0000
@@ -229,7 +229,7 @@
$self->invoke_event( on_tick => );
- $self->start;
+ $self->start unless delete $self->{please_stop};
} );
}