Every.pm

I want this to happen every 10 cycles.

I want this to happen every 30 seconds.

Every: Do It Every Now And Then

We've all done it the ugly way:

while (<>)
{
    ...
    $i++;
    print_stats() unless $i % 10# fires at 0, 10, 20, ...
}

Every: Do It Till It Hertz

We've all stored time() somewhere:

my $then = time();

while (<>)
{
    ...
    my $now = time();
    if ($now - $then > 30# fires at 30, 60, 90, ... seconds
    {
        print_stats();
        $then = $now;
    }
}

every(10)

This is simpler:

use Every;

while (<>)
{
    print_stats() if every(10); # fires at 10, 20, 30, ...
}

every(seconds => 10)

This is simpler too:

use Every;

while (<>)
{
    print_stats() if every(seconds => 30); # fires at 30, 60, 90, ... seconds
}

Caveats

every(10) fires at 10 and up, not at 0. This is a feature but I can add an option to override it. I have not needed it and Jerrad Pierce, who suggested it, said he doesn't need it either.

The time-based counters are in seconds only. It's trivial to put in millisecond counters with Time::HiRes but I have not needed them.

Strange cases

Multiple every() calls on the same line: no problem. Devel::CallSite will identify the call site uniquely. You can, however, supply your own identifiers as a list to every() if you need more control, but you can't (currently) reuse the same counter. I can add that if anyone needs it but so far I haven't.

Use it!

Just use it. Maybe it will be in the core some day.