Webqq/Message/Queue.pm untested

filter: Statementstmt 0.0% 0 / 42 Branchbran 0.0% 0 / 18 Conditioncond 0.0% 0 / 3 MC/DCmcdc 0.0% 0 / 2 Subroutinesub 0.0% 0 / 4 Podpod 0.0% 0 / 4 totaltotal 0.0% 0 / 73 CC 10 SCAR 31.8
CC
10
Cov
0%
new
30.0
put
30.0
get
6.0
CRAP 24.2
1 package Mojo::Webqq::Message::Queue;
2 $Mojo::Webqq::Message::Queue::LAST_GET_TIME = undef;
3 $Mojo::Webqq::Message::Queue::GET_INTERVAL = 3;
4 sub new{
5 my $class = shift;
6 my $callback_for_get ;
7 my $callback_for_put ;
8 my $callback_for_delay ;
9 my $ioloop ;
10 if(@_ == 1){
11 $callback_for_get = shift;
12 }
13 else{
14 my %opt = @_;
15 $callback_for_get = $opt{get};
16 $callback_for_put = $opt{put};
17 $callback_for_delay = $opt{delay};
18 $ioloop = $opt{ioloop};
19 }
20 my $self = {
21 ioloop => $ioloop,
22 queue => [],
23 callback_for_get => undef,
24 callback_for_delay => undef,
25 callback_for_put => undef,
26 callback_for_get_bak => undef,
27 };
28 $self->{callback_for_get} = $callback_for_get if ref $callback_for_get eq "CODE";
29 $self->{callback_for_put} = $callback_for_put if ref $callback_for_put eq "CODE";
30 $self->{callback_for_delay} = $callback_for_delay if ref $callback_for_delay eq "CODE";
31 return bless $self,$class;
32 }
33 sub put{
34 my $self = shift;
35 die "Mojo::Webqq::Message::Queue->put()失败,请检查是否已经设置了队列get()回调\n"
36 unless ref $self->{callback_for_get} eq 'CODE';
37 push @{ $self->{queue} } ,$_[0];
38 if(defined $self->{ioloop} and ref $self->{callback_for_delay} eq "CODE"){
39 my $delay = 0;
40 my $now = time;
41 if(defined $Mojo::Webqq::Message::Queue::LAST_GET_TIME){
42 $delay = $now<$Mojo::Webqq::Message::Queue::LAST_GET_TIME+$Mojo::Webqq::Message::Queue::GET_INTERVAL?
43 $Mojo::Webqq::Message::Queue::LAST_GET_TIME+$Mojo::Webqq::Message::Queue::GET_INTERVAL-$now
44 : 0;
45 }
46 $self->{ioloop}->timer($delay,sub{
47 $self->{callback_for_delay}->($self->{queue});
48 $self->_notify_to_get();
49 });
50 $Mojo::Webqq::Message::Queue::LAST_GET_TIME = $now+$delay;
51 }
52 else{
53 $self->_notify_to_get();
54 }
55 }
56 sub get{
57 my $self = shift;
58 my $cb = shift;
59 die "Mojo::Webqq::Message::Queue->get()仅接受一个函数引用\n" unless ref $cb eq 'CODE';
60 $self->{callback_for_get} = $cb;
61 $self->{callback_for_get_bak} = $cb;
62 }
63 sub _notify_to_get{
64 my $self = shift;
65 my $msg = shift @{$self->{queue}};
66 $self->{callback_for_get}->($msg);
67 }
68  
69 1;