| 1 | package Mojo::Weixin::Client::Cron; | ||
| 2 | use POSIX qw(mktime); | ||
| 3 | BEGIN{ | ||
| 4 | our $is_module_ok = 0; | ||
| 5 | eval{ | ||
| 6 | require Time::Piece; | ||
| 7 | require Time::Seconds; | ||
| 8 | Time::Piece->import; | ||
| 9 | Time::Seconds->import; | ||
| 10 | }; | ||
| 11 | $is_module_ok = 1 if not $@; | ||
| 12 | } | ||
| 13 | sub add_job{ | ||
| 14 | my $self = shift; | ||
| 15 | if(not $is_module_ok){ | ||
| 16 | $self->error("调用add_job方法请先确保安装模块 Time::Piece 和 Time::Seconds"); | ||
| 17 | return; | ||
| 18 | } | ||
| 19 | my($type,$nt,$callback) = @_; | ||
| 20 | my $t = $nt; | ||
| 21 | if(ref $callback ne 'CODE'){ | ||
| 22 | $self->die("设置的callback无效\n"); | ||
| 23 | } | ||
| 24 | if(ref $nt eq "CODE"){ | ||
| 25 | $t = $nt->(); | ||
| 26 | } | ||
| 27 | my $time = {}; | ||
| 28 | if(ref $t eq "HASH"){ | ||
| 29 | $time = $t; | ||
| 30 | } | ||
| 31 | else{ | ||
| 32 | my($hour,$minute,$second) = split /:/,$t; | ||
| 33 | $second = 0 if not defined $second ; | ||
| 34 | $time = {hour => $hour,minute => $minute,second=> $second}; | ||
| 35 | } | ||
| 36 | $self->debug("计划任务[$type]添加成功,时间设定: " . join(":",map {$_!=0?$_:"00"} ($time->{hour},$time->{minute},$time->{second})) ); | ||
| 37 | my $delay; | ||
| 38 | #my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime; | ||
| 39 | my @now = localtime; | ||
| 40 | my $now = mktime(@now); | ||
| 41 | my @next = @{[@now]}; | ||
| 42 | for my $k (keys %$time){ | ||
| 43 | $k eq 'year' ? ($next[5]=$time->{$k}-1900) | ||
| 44 | : $k eq 'month' ? ($next[4]=$time->{$k}-1) | ||
| 45 | : $k eq 'day' ? ($next[3]=$time->{$k}) | ||
| 46 | : $k eq 'hour' ? ($next[2]=$time->{$k}) | ||
| 47 | : $k eq 'minute' ? ($next[1]=$time->{$k}) | ||
| 48 | : $k eq 'second' ? ($next[0]=$time->{$k}) | ||
| 49 | : next; | ||
| 50 | } | ||
| 51 | |||
| 52 | my $next = mktime(@next); | ||
| 53 | $now = localtime($now); | ||
| 54 | $next = localtime($next); | ||
| 55 | |||
| 56 | if($now >= $next){ | ||
| 57 | if( $time->{month} ) { | ||
| 58 | $next->add_years(1); | ||
| 59 | } | ||
| 60 | elsif( $time->{day} ) { | ||
| 61 | $next->add_months(1); | ||
| 62 | } | ||
| 63 | elsif( $time->{hour} ) { | ||
| 64 | $next += ONE_DAY; | ||
| 65 | } | ||
| 66 | elsif( $time->{minute} ) { | ||
| 67 | $next += ONE_HOUR; | ||
| 68 | } | ||
| 69 | elsif( $time->{second} ) { | ||
| 70 | $next += ONE_MINUTE; | ||
| 71 | } | ||
| 72 | } | ||
| 73 | |||
| 74 | $self->debug("计划任务[$type]下一次触发时间为:" . $next->strftime("%Y/%m/%d %H:%M:%S")); | ||
| 75 | $delay = $next - $now; | ||
| 76 | $self->timer($delay,sub{ | ||
| 77 | eval{ | ||
| 78 | $callback->(); | ||
| 79 | }; | ||
| 80 | $self->error($@) if $@; | ||
| 81 | $self->add_job($type,$nt,$callback); | ||
| 82 | }); | ||
| 83 | } | ||
| 84 | 1; |