File Coverage

blib/lib/MangoX/Queue/Delay.pm
Criterion Covered Total %
statement 6 24 25.0
branch 0 4 0.0
condition n/a
subroutine 2 4 50.0
pod 0 2 0.0
total 8 34 23.5


line stmt bran cond sub pod time code
1             package MangoX::Queue::Delay;
2              
3 12     12   62 use Mojo::Base -base;
  12         21  
  12         85  
4 12     12   1631 use Mojo::Log;
  12         28  
  12         62  
5              
6             has start => sub { $ENV{MANGOX_QUEUE_DELAY_START} // 0.1 };
7             has current => sub { $ENV{MANGOX_QUEUE_DELAY_START} // 0.1 };
8             has increment => sub { $ENV{MANGOX_QUEUE_DELAY_INCREMENT} // 0.1 };
9             has maximum => sub { $ENV{MANGOX_QUEUE_DELAY_MAXIMUM} // 10 };
10              
11             has log => sub { Mojo::Log->new->level('error') };
12              
13             sub reset {
14 0     0 0   my ($self) = @_;
15            
16 0           $self->log->debug("Reset delay to " . $self->start . " seconds");
17              
18 0           $self->current($self->start);
19             }
20              
21             sub wait {
22 0     0 0   my ($self, $callback) = @_;
23              
24 0           my $delay = $self->current;
25 0           $self->log->debug("Current delay is $delay seconds");
26              
27 0           my $incremented = $delay + $self->increment;
28 0           $self->log->debug("New delay is $incremented seconds");
29              
30 0 0         if($incremented > $self->maximum) {
31 0           $self->log->debug("Limiting delay to maximum " . $self->maximum . " seconds");
32 0           $incremented = $self->maximum;
33             }
34              
35 0           $self->current($incremented);
36              
37 0 0         if($callback) {
38 0           $self->log->debug("Non-blocking delay for $delay seconds");
39 0           Mojo::IOLoop->timer($delay => $callback);
40             } else {
41 0           $self->log->debug("Sleeping for $delay seconds");
42 0           sleep $delay;
43             }
44              
45 0           return $delay;
46             }
47              
48             1;