On Tue, Dec 14, 1999 at 09:03:51PM -0800, [EMAIL PROTECTED] wrote:
> I'm trying to solve a problem that I think should be able to use
> Event.  I hope someone can point me in the right direction.
> 
> The basic structure is that I have a several tasks to perform repeatedly,
> but I don't know when I want to do any given task again until I'm doing it.
> Something like:
> 
> sub callback{
>    <do something>;
>    <figure out when we need to do it again>;
>    <arrange to do it again at the appointed time>;
> }
> 
> I was hoping to do something like reset the 'after' attribute of the
> event while I was in it, and then call again.  The following code is
> clearly not right, because there is no 'after' method in Event::timer,
> but I hope it conveys what I'm trying to do:
> 
> #!/usr/local/bin/perl
> 
> use Event qw( loop );
> 
> $w = Event->timer(after => 1);
> 
> $w->cb(sub {
>     print scalar localtime, "\n";
>     $w->after(rand(10.));
>     $w->again;
> });
> loop();
> 
> Can anyone suggest a better approach for this kind of problem?

Joshua Pritikin wrote:
>How about this?
>
>package Event::timer;  # UNTESTED
>sub after {
>  my ($w, $sec) = @_;
>  $w->at(Event::time() + $sec);
>}

Not quite.  It didn't work the first time, so I tried calling the at()
method directly.  Viz:

$w = Event->timer(after => 1);

$w->cb(sub {
    $now = Event::time();
    $next = $now + rand(20.);
    print "Now: ", scalar localtime($now), " Next: ", scalar localtime($next), "\n";
    $w->at($next);
    $w->again;
});
loop();

The output looks like:

[jsalmon@gw]$ ./ev.pl
Now: Wed Dec 15 09:04:02 1999 Next: Wed Dec 15 09:04:12 1999
Now: Wed Dec 15 09:04:04 1999 Next: Wed Dec 15 09:04:23 1999
Now: Wed Dec 15 09:04:06 1999 Next: Wed Dec 15 09:04:12 1999
Now: Wed Dec 15 09:04:08 1999 Next: Wed Dec 15 09:04:19 1999

The events happen every two seconds, regardless of the value passed to
$w->at().

I guessed that the 'after' attribute in the constructor was causing me trouble.
So I tried the following constructor instead:

$w = Event->timer(at => Event::time() + 1);

Then I got:

[jsalmon@gw]$ ./ev.pl
Now: Wed Dec 15 09:06:43 1999 Next: Wed Dec 15 09:06:49 1999
Event: trapped error in '?? ev.pl:5': Repeating timer with no interval at 
/usr/lib/perl5/site_perl/5.005/i386-linux/Event.pm line 145

Other ideas?

Thanks,
John Salmon

Reply via email to