Algorithm-TokenBucket
view release on metacpan or search on metacpan
8384858687888990919293949596979899100101102103- count($)
This method removes _N_ (or all
if
there are fewer than _N_ available)
tokens from the bucket. It does not
return
a meaningful value.
-
until
($)
This method returns the number of seconds
until
_N_ tokens can be removed
from the bucket. It is especially useful in multitasking environments like
`conform(
$N
)` check in `
until
(
$N
)` seconds instead of checking
repeatedly.
Note that `
until
()` does not take into account `burst size`. This means
that a bucket will not conform to _N_ even
after
sleeping
for
`
until
(
$N
)`
seconds
if
_N_ is greater than `burst size`.
- get\_token\_count()
Returns the current number of tokens in the bucket. This method may be
112113114115116117118119120121122123124125126127128129130131132Imagine a rate limiter
for
a mail sending application. We would like to
allow 2 mails per minute but
no
more than 20 mails per hour.
my
$rl1
= Algorithm::TokenBucket->new(2/60, 1);
my
$rl2
= Algorithm::TokenBucket->new(20/3600, 10);
# "bursts" of 10 to ease the lag but $rl1 enforces
# 2 per minute, so it won't flood
while
(
my
= get_next_mail) {
until
(
$rl1
->conform(1) &&
$rl2
->conform(1)) {
busy_wait;
}
->take_off;
$rl1
->count(1);
$rl2
->count(1);
}
Now, let's fix the CPU-hogging example from [
"SYNOPSIS"
](
#synopsis) using
the [
"until($)"
](
#until) method.
my
$bucket
= Algorithm::TokenBucket->new(100 / 3600, 5);
lib/Algorithm/TokenBucket.pm view on Meta::CPAN
174175176177178179180181182183184185186187188189190191192193194
$self
->_token_flow;
(
$self
->{_tokens} -=
$size
) < 0 and
$self
->{_tokens} = 0;
}
=item until($)
This method returns the number of seconds until I<N> tokens can be removed
from the bucket. It is especially useful in multitasking environments like
L<POE> where you cannot busy-wait. One can safely schedule the next
C<< conform($N) >> check in C<< until($N) >> seconds instead of checking
repeatedly.
Note that C<until()> does not take into account C<burst size>. This means
that a bucket will not conform to I<N> even after sleeping for C<< until($N) >>
seconds if I<N> is greater than C<burst size>.
=cut
sub
until
{
lib/Algorithm/TokenBucket.pm view on Meta::CPAN
233234235236237238239240241242243244245246247248249250251252253Imagine a rate limiter
for
a mail sending application. We would like to
allow 2 mails per minute but
no
more than 20 mails per hour.
my
$rl1
= Algorithm::TokenBucket->new(2/60, 1);
my
$rl2
= Algorithm::TokenBucket->new(20/3600, 10);
# "bursts" of 10 to ease the lag but $rl1 enforces
# 2 per minute, so it won't flood
while
(
my
= get_next_mail) {
until
(
$rl1
->conform(1) &&
$rl2
->conform(1)) {
busy_wait;
}
->take_off;
$rl1
->count(1);
$rl2
->count(1);
}
Now, let's fix the CPU-hogging example from L</SYNOPSIS> using
the L</
until
($)> method.
my
$bucket
= Algorithm::TokenBucket->new(100 / 3600, 5);
( run in 0.333 second using v1.01-cache-2.11-cpan-496ff517765 )