Velocity Reviews

Velocity Reviews (http://www.velocityreviews.com/forums/index.php)
-   Perl Misc (http://www.velocityreviews.com/forums/f67-perl-misc.html)
-   -   every(seconds => 4) (http://www.velocityreviews.com/forums/t906605-every-seconds-4-a.html)

Ted Zlatanov 02-29-2008 06:30 PM

every(seconds => 4)
 
I've extended the every() function I discussed before to handle the
'seconds' syntax, so you can say

while (<>)
{
...
if (every(seconds=>60))
{
# do this every minute when input arrives
}
elsif (every(5000) || every(943, "second one")) # distinguish the second call's hash entry
{
}
}

Here's my implementation, which preserves the semantics of the original
every(N) function as well. I'm curious if anyone has ideas for more
things I can add. I am debating if it's worth putting on CPAN (I don't
know of anything like it already on CPAN). It seems like a really
simple piece of code that doesn't necessarily merit its own module, but
it's really useful to me...

Ted

{
my %counters;
my %time_counters;
sub every
{
my ($div, @id) = @_;

if ($div eq 'seconds')
{
$div = shift @id; # the number follows the 'seconds' string

$time_counters{caller(), $div, @id} ||= time;

my $then = $time_counters{caller(), $div, @id};
my $diff = time - ($then + $div);
return ($diff >= 0) ? ($time_counters{caller(), $div, @id} = time) : 0;
}
# else...
return !(++$counters{ caller(), $div, @id } % $div);
}
}


All times are GMT. The time now is 01:34 PM.

Powered by vBulletin®. Copyright ©2000 - 2014, vBulletin Solutions, Inc.
SEO by vBSEO ©2010, Crawlability, Inc.