From 29e1c7d49f378781d119dddba5efa4c086843131 Mon Sep 17 00:00:00 2001 From: Michael Conrad Date: Fri, 21 Aug 2015 14:09:58 -0400 Subject: [PATCH] Fixed timer lifespan in 2013 advent cal async example This example appeared to work, but actually most requests were having their timer cut short by the next request, because there was only one global variable, and the program needed to hold refs to multiple concurrent timers. Solved in the simplest possible way by moving the timer ref inside the timer callback to create a circular reference, though aa better way would be to hold the timer ref in a global pool and not form the circular ref in the first place. But, that's more code... --- 1to4-Nonblocking-Streaming/bin/five-times-evented.psgi | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/1to4-Nonblocking-Streaming/bin/five-times-evented.psgi b/1to4-Nonblocking-Streaming/bin/five-times-evented.psgi index 2ea48ef..4d83aea 100644 --- a/1to4-Nonblocking-Streaming/bin/five-times-evented.psgi +++ b/1to4-Nonblocking-Streaming/bin/five-times-evented.psgi @@ -2,18 +2,19 @@ use AnyEvent; use warnings; use strict; -my $watcher; my $timer_model = sub { my $writer = shift; my $count = 1; - $watcher = AnyEvent->timer( + my $timer; + $timer = AnyEvent->timer( after => 0, interval => 1, cb => sub { $writer->write(scalar localtime ."\n"); if(++$count > 5) { $writer->close; - undef $watcher; + # this cancels the timer, and breaks a circular reference + undef $timer; } }); }; @@ -26,6 +27,7 @@ my $psgi_app = sub { [200, [ 'Content-Type' => 'text/plain' ]]); $timer_model->($writer); - + # our timer lives on via a circular reference. + # return value is ignored }; };