File Coverage

blib/lib/Webqq/Client/Cron.pm
Criterion Covered Total %
statement 12 45 26.6
branch 0 30 0.0
condition n/a
subroutine 4 6 66.6
pod 0 1 0.0
total 16 82 19.5


line stmt bran cond sub pod time code
1             package Webqq::Client::Cron;
2 1     1   8 use Webqq::Client::Util qw(console_stderr console);
  1         2  
  1         75  
3 1     1   7 use POSIX qw(mktime);
  1         2  
  1         9  
4 1     1   655 use Time::Piece;
  1         6889  
  1         4  
5 1     1   59 use Time::Seconds;
  1         2  
  1         406  
6             sub add_job{
7 0     0 0   my $self = shift;
8             #AE::now_update;
9 0           my($type,$t,$callback) = @_;
10 0 0         if(ref $callback ne 'CODE'){
11 0           console_stderr("Webqq::Client::Cron->add_job()设置的callback无效\n");
12 0           exit;
13             }
14 0           my($hour,$minute) = split /:/,$t;
15 0           my $time = {hour => $hour,minute => $minute,second=>0};
16 0           my $delay;
17             #my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime;
18 0           my @now = localtime;
19 0           my $now = mktime(@now);
20 0           my @next = @{[@now]};
  0            
21 0           for my $k (keys %$time){
22 0 0         $k eq 'year' ? ($next[5]=$time->{$k}-1900)
    0          
    0          
    0          
    0          
    0          
23             : $k eq 'month' ? ($next[4]=$time->{$k}-1)
24             : $k eq 'day' ? ($next[3]=$time->{$k})
25             : $k eq 'hour' ? ($next[2]=$time->{$k})
26             : $k eq 'minute' ? ($next[1]=$time->{$k})
27             : $k eq 'second' ? ($next[0]=$time->{$k})
28             : next;
29             }
30              
31 0           my $next = mktime(@next);
32 0           $now = localtime($now);
33 0           $next = localtime($next);
34              
35 0 0         if($now >= $next){
36 0 0         if( $time->{month} ) {
    0          
    0          
    0          
    0          
37 0           $next->add_years(1);
38             }
39             elsif( $time->{day} ) {
40 0           $next->add_months(1);
41             }
42             elsif( $time->{hour} ) {
43 0           $next += ONE_DAY;
44             }
45             elsif( $time->{minute} ) {
46 0           $next += ONE_HOUR;
47             }
48             elsif( $time->{second} ) {
49 0           $next += ONE_MINUTE;
50             }
51             }
52            
53 0 0         console "[$type]下一次触发时间为:" . $next->strftime("%Y/%m/%d %H:%M:%S\n") if $self->{debug};
54 0           $delay = $next - $now;
55 0           my $rand_watcher_id = rand();
56             $self->{watchers}{$rand_watcher_id} = AE::timer $delay,0,sub{
57 0     0     delete $self->{watchers}{$rand_watcher_id};
58 0           eval{
59 0           $callback->();
60             };
61 0 0         console $@ if $@;
62 0           $self->add_job($type,$t,$callback);
63 0           };
64             }
65             1;