blib/lib/Schedule/Cron.pm

filter: Statementstmt 72.0% 448 / 622 Branchbran 58.7% 215 / 366 Conditioncond 58.2% 110 / 189 MC/DCmcdc 34.5% 37 / 107 Subroutinesub 85.7% 36 / 42 Podpod 85.7% 12 / 14 totaltotal 64.0% 858 / 1340 CC 262 SCAR 38.8
CC
262
Cov
66%
report_exectime_bug
272.0
run
101.7
_execute
68.9
CRAP 48.5
↑ Summary
1 #!/usr/bin/perl -w
2  
3 =encoding utf8
4  
5 =head1 NAME
6  
7 Cron - cron-like scheduler for Perl subroutines
8  
9 =head1 SYNOPSIS
10  
11 use Schedule::Cron;
12  
13 # Subroutines to be called
14 sub dispatcher {
15 print "ID: ",shift,"\n";
16 print "Args: ","@_","\n";
17 }
18  
19 sub check_links {
20 # do something...
21 }
22  
23 # Create new object with default dispatcher
24 my $cron = new Schedule::Cron(\&dispatcher);
25  
26 # Load a crontab file
27 $cron->load_crontab("/var/spool/cron/perl");
28  
29 # Add dynamically crontab entries
30 $cron->add_entry("3 4 * * *",ROTATE => "apache","sendmail");
31 $cron->add_entry("0 11 * * Mon-Fri",\&check_links);
32  
33 # Run scheduler
34 $cron->run(detach=>1);
35
36  
37 =head1 DESCRIPTION
38  
39 This module provides a simple but complete cron like scheduler. I.e this
40 module can be used for periodically executing Perl subroutines. The dates and
41 parameters for the subroutines to be called are specified with a format known
42 as crontab entry (see L<"METHODS">, C<add_entry()> and L<crontab(5)>)
43  
44 The philosophy behind C<Schedule::Cron> is to call subroutines periodically
45 from within one single Perl program instead of letting C<cron> trigger several
46 (possibly different) Perl scripts. Everything under one roof. Furthermore,
47 C<Schedule::Cron> provides mechanism to create crontab entries dynamically,
48 which isn't that easy with C<cron>.
49  
50 C<Schedule::Cron> knows about all extensions (well, at least all extensions I'm
51 aware of, i.e those of the so called "Vixie" cron) for crontab entries like
52 ranges including 'steps', specification of month and days of the week by name,
53 or coexistence of lists and ranges in the same field. It even supports a bit
54 more (like lists and ranges with symbolic names).
55  
56 =head1 METHODS
57  
58 =over 4
59  
60 =cut
61  
62 #'
63  
64 package Schedule::Cron;
65  
66 18 ▶use Time::ParseDate;
Subroutine BEGIN: called CC=1 SCAR=0.0
67 18 ▶use Data::Dumper;
Subroutine BEGIN: called CC=1 SCAR=0.0
68  
69 18 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
70 18 ▶use vars qw($VERSION $DEBUG);
Subroutine BEGIN: called CC=1 SCAR=0.0
71 18 ▶use subs qw(dbg);
Subroutine BEGIN: called CC=1 SCAR=0.0
72  
73 18 my $HAS_POSIX;
74  
75 18 ▶BEGIN {
Subroutine BEGIN: called CC=2 SCAR=7.0
76 18 eval {
77 18 require POSIX;
78 18 import POSIX ":sys_wait_h";
79 };
80 18 ▶ $HAS_POSIX = $@ ? 0 : 1;
Branch: 1 branch
BranchTrueFalseTotal
$@ ? : 0 18 18
81 }
82  
83  
84 18 $VERSION = "1.07";
85  
86 18 our $DEBUG = 0;
87 18 my %STARTEDCHILD = ();
88  
89 18 my @WDAYS = qw(
90 Sunday
91 Monday
92 Tuesday
93 Wednesday
94 Thursday
95 Friday
96 Saturday
97 Sunday
98 );
99  
100 18 my @ALPHACONV = (
101 { },
102 { },
103 { },
104 { qw(jan 1 feb 2 mar 3 apr 4 may 5 jun 6 jul 7 aug 8
105 sep 9 oct 10 nov 11 dec 12) },
106 { qw(sun 0 mon 1 tue 2 wed 3 thu 4 fri 5 sat 6)},
107 { }
108 );
109 18 my @RANGES = (
110 [ 0,59 ],
111 [ 0,23 ],
112 [ 0,31 ],
113 [ 0,12 ],
114 [ 0,7 ],
115 [ 0,59 ]
116 );
117  
118 18 my @LOWMAP = (
119 {},
120 {},
121 { 0 => 1},
122 { 0 => 1},
123 { 7 => 0},
124 {},
125 );
126  
127  
128 # Currently, there are two ways for reaping. One, which only waits explicitly
129 # on PIDs it forked on its own, and one which waits on all PIDs (even on those
130 # it doesn't forked itself). The later has been proved to work on Win32 with
131 # the 64 threads limit (RT #56926), but not when one creates forks on ones
132 # own. The specific reaper works for RT #55741.
133  
134 # It tend to use the specific one, if it also resolves RT #56926. Both are left
135 # here for reference until a decision has been done for 1.01
136  
137 5 ▶sub REAPER {
Subroutine REAPER: called CC=1 SCAR=0.0
Pod undocumented
138 5 &_reaper_all();
139 }
140  
141 # Specific reaper
142 0 ▶sub _reaper_specific {
Subroutine _reaper_specific: not called CC=8 SCAR=39.6
143 0 ▶ local ($!,%!,$?);
Subroutine BEGIN: called CC=1 SCAR=0.2
144 0 ▶ if ($HAS_POSIX)
Branch: 1 branch
BranchTrueFalseTotal
if ($HAS_POSIX) { } 0 0 0
145 {
146 0 foreach my $pid (keys %STARTEDCHILD) {
147 0 ▶ if ($STARTEDCHILD{$pid}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($STARTEDCHILD{$pid}) 0 0 0
148 0 ▶ my $res = $HAS_POSIX ? waitpid($pid, WNOHANG) : waitpid($pid,0);
Branch: 1 branch
BranchTrueFalseTotal
$HAS_POSIX ? : 0 0 0
149 0 ▶ if ($res > 0) {
Branch: 1 branch
BranchTrueFalseTotal
if ($res > 0) 0 0 0
150 # We reaped a truly running process
151 0 $STARTEDCHILD{$pid} = 0;
152 0 ▶ dbg "Reaped child $res" if $DEBUG;
Branch: 1 branch
BranchTrueFalseTotal
if $Schedule::Cron::DEBUG 0 0 0
153 }
154 }
155 }
156 }
157 else
158 {
159 0 my $waitedpid = 0;
160 0 ▶ while($waitedpid != -1) {
Branch: 1 branch
BranchTrueFalseTotal
if ($waitedpid != -1) 0 0 0
161 0 $waitedpid = wait;
162 }
163 }
164 }
165  
166 # Catch all reaper
167 5 ▶sub _reaper_all {
Subroutine _reaper_all: called CC=9 SCAR=22.9
168 #local ($!,%!,$?,${^CHILD_ERROR_NATIVE});
169  
170 # Localizing ${^CHILD_ERROR_NATIVE} breaks signalhander.t which checks that
171 # chained SIGCHLD handlers are called. I don't know why, though, hence I
172 # leave it out for now. See #69916 for some discussion why this handler
173 # might be needed.
174 5 local ($!,%!,$?);
175 4 my $kid;
176 do
177 4 ▶ {
Branch: 1 branch
BranchTrueFalseTotal
$kid != 0 and $kid != -1 and do { do { $kid = $HAS_POSIX ? waitpid(-1, 1) : wait; dbg("Kid: $kid") if $DEBUG; if ($kid != 0 and $kid != -1 and defined $STARTEDCHILD{$kid}) { $STARTEDCHILD{$kid} = 0; dbg("Reaped child $kid") if $DEBUG; } } } 1 4 5
Condition66%2/3
$kid != 0 and $kid != -1
!ll&&!rl&&r
401
MC/DC50%1/2
$kid != 0 and $kid != -1
$kid != 0 $kid != -1
Truth table66%2/3
A and B
A= $kid != 0B= $kid != -1
ABresult
0X0
100
111
178 # Only on POSIX systems the wait will return immediately
179 # if there are no finished child processes. Simple 'wait'
180 # waits blocking on childs.
181 5 ▶ $kid = $HAS_POSIX ? waitpid(-1, WNOHANG) : wait;
Branch: 1 branch
BranchTrueFalseTotal
$HAS_POSIX ? : 5 0 5
182 5 ▶ dbg "Kid: $kid" if $DEBUG;
Branch: 1 branch
BranchTrueFalseTotal
if $DEBUG 0 5 5
183 5 ▶ if ($kid != 0 && $kid != -1 && defined $STARTEDCHILD{$kid})
Branch: 1 branch
BranchTrueFalseTotal
if ($kid != 0 and $kid != -1 and defined $STARTEDCHILD{$kid}) 1 4 5
Condition66%4/6
$kid != 0 and $kid != -1 and defined $STARTEDCHILD{$kid}
!ll&&!rl&&r
401
$kid != 0 and $kid != -1
!ll&&!rl&&r
401
MC/DC33%1/3
$kid != 0 and $kid != -1 and defined $STARTEDCHILD{$kid}
$kid != 0 $kid != -1 defined $STARTEDCHILD{$kid}
Truth table50%2/4
A and B and C
A= $kid != 0B= $kid != -1C= defined $STARTEDCHILD{$kid}
ABCresult
0XX0
10X0
1100
1111
184 {
185 # We don't delete the hash entry here to avoid an issue
186 # when modifying global hash from multiple threads
187 1 $STARTEDCHILD{$kid} = 0;
188 1 ▶ dbg "Reaped child $kid" if $DEBUG;
Branch: 1 branch
BranchTrueFalseTotal
if $DEBUG 0 1 1
189 }
190 } while ($kid != 0 && $kid != -1);
191  
192 # Note to myself: Is the %STARTEDCHILD hash really necessary if we use -1
193 # for waiting (i.e. for waiting on any child ?). In the current
194 # implementation, %STARTEDCHILD is not used at all. It would be only
195 # needed if we iterate over it to wait on pids specifically.
196 }
197  
198 # Cleaning is done in extra method called from the main
199 # process in order to avoid event handlers modifying this
200 # global hash which can lead to memory errors.
201 # See RT #55741 for more details on this.
202 # This method is called in strategic places.
203 sub _cleanup_process_list
204 14 ▶{
Subroutine _cleanup_process_list: called CC=5 SCAR=16.4
205 14 my ($self, $cfg) = @_;
206
207 # Cleanup processes even on those systems, where the SIGCHLD is not
208 # propagated. Only do this for POSIX, otherwise this call would block
209 # until all child processes would have been finished.
210 # See RT #56926 for more details.
211  
212 # Do not cleanup if nofork because jobs that fork will do their own reaping.
213 14 ▶ &REAPER() if $HAS_POSIX && !$cfg->{nofork};
Branch: 1 branch
BranchTrueFalseTotal
if $HAS_POSIX and not $cfg->{"nofork"} 4 10 14
Condition66%2/3
$HAS_POSIX and not $cfg->{"nofork"}
!ll&&!rl&&r
0104
MC/DC50%1/2
$HAS_POSIX and not $cfg->{"nofork"}
$HAS_POSIX not $cfg->{"nofork"}
Truth table66%2/3
A and not(B)
A= $HAS_POSIXB= not $cfg->{"nofork"}
ABresult
0X0
100
111
214  
215 # Delete entries from this global hash only from within the main
216 # thread/process. Hence, this method must not be called from within
217 # a signalhandler
218 13 for my $k (keys %STARTEDCHILD)
219 {
220 4 ▶ delete $STARTEDCHILD{$k} unless $STARTEDCHILD{$k};
Branch: 1 branch
BranchTrueFalseTotal
unless $STARTEDCHILD{$k} 0 4 4
221 }
222 }
223  
224 =item $cron = new Schedule::Cron($dispatcher,[extra args])
225  
226 Creates a new C<Cron> object. C<$dispatcher> is a reference to a subroutine,
227 which will be called by default. C<$dispatcher> will be invoked with the
228 arguments parameter provided in the crontab entry if no other subroutine is
229 specified. This can be either a single argument containing the argument
230 parameter literally has string (default behavior) or a list of arguments when
231 using the C<eval> option described below.
232  
233 The date specifications must be either provided via a crontab like file or
234 added explicitly with C<add_entry()> (L<"add_entry">).
235  
236 I<extra_args> can be a hash or hash reference for additional arguments. The
237 following parameters are recognized:
238  
239 =over
240  
241 =item file => <crontab>
242  
243  
244 Load the crontab entries from <crontab>
245  
246 =item eval => 1
247  
248 Eval the argument parameter in a crontab entry before calling the subroutine
249 (instead of literally calling the dispatcher with the argument parameter as
250 string)
251  
252 =item nofork => 1
253  
254 Don't fork when starting the scheduler. Instead, the jobs are executed within
255 current process. In your executed jobs, you have full access to the global
256 variables of your script and hence might influence other jobs running at a
257 different time. This behavior is fundamentally different to the 'fork' mode,
258 where each jobs gets its own process and hence a B<copy> of the process space,
259 independent of each other job and the main process. This is due to the nature
260 of the C<fork> system call.
261  
262 =item nostatus => 1
263  
264 Do not update status in $0. Set this if you don't want ps to reveal the internals
265 of your application, including job argument lists. Default is 0 (update status).
266  
267 =item skip => 1
268  
269 Skip any pending jobs whose time has passed. This option is only useful in
270 combination with C<nofork> where a job might block the execution of the
271 following jobs for quite some time. By default, any pending job is executed
272 even if its scheduled execution time has already passed. With this option set
273 to true all pending which would have been started in the meantime are skipped.
274  
275 =item catch => 1
276  
277 Catch any exception raised by a job. This is especially useful in combination with
278 the C<nofork> option to avoid stopping the main process when a job raises an
279 exception (dies).
280  
281 =item after_job => \&after_sub
282  
283 Call a subroutine after a job has been run. The first argument is the return
284 value of the dispatched job, the reminding arguments are the arguments with
285 which the dispatched job has been called.
286  
287 Example:
288  
289 my $cron = new Schedule::Cron(..., after_job => sub {
290 my ($ret,@args) = @_;
291 print "Return value: ",$ret," - job arguments: (",join ":",@args,")\n";
292 });
293  
294 =item log => \&log_sub
295  
296 Install a logging subroutine. The given subroutine is called for several events
297 during the lifetime of a job. This method is called with two arguments: A log
298 level of 0 (info),1 (warning) or 2 (error) depending on the importance of the
299 message and the message itself.
300  
301 For example, you could use I<Log4perl> (L<http://log4perl.sf.net>) for logging
302 purposes for example like in the following code snippet:
303  
304 use Log::Log4perl;
305 use Log::Log4perl::Level;
306  
307 my $log_method = sub {
308 my ($level,$msg) = @_;
309 my $DBG_MAP = { 0 => $INFO, 1 => $WARN, 2 => $ERROR };
310  
311 my $logger = Log::Log4perl->get_logger("My::Package");
312 $logger->log($DBG_MAP->{$level},$msg);
313 }
314
315 my $cron = new Schedule::Cron(.... , log => $log_method);
316  
317 =item loglevel => <-1,0,1,2>
318  
319 Restricts logging to the specified severity level or below. Use 0 to have all
320 messages generated, 1 for only warnings and errors and 2 for errors only.
321 Default is 0 (all messages). A loglevel of -1 (debug) will include job
322 argument lists (also in $0) in the job start message logged with a level of 0
323 or above. You may have security concerns with this. Unless you are debugging,
324 use 0 or higher. A value larger than 2 will disable logging completely.
325  
326 Although you can filter in your log routine, generating the messages can be
327 expensive, for example if you pass arguments pointing to large hashes. Specifying
328 a loglevel avoids formatting data that your routine would discard.
329  
330 =item processprefix => <name>
331  
332 Cron::Schedule sets the process' name (i.e. C<$0>) to contain some informative
333 messages like when the next job executes or with which arguments a job is
334 called. By default, the prefix for this labels is C<Schedule::Cron>. With this
335 option you can set it to something different. You can e.g. use C<$0> to include
336 the original process name. You can inhibit this with the C<nostatus> option, and
337 prevent the argument display by setting C<loglevel> to zero or higher.
338  
339 =item processname => <name>
340  
341 Set the process name (i.e. C<$0>) to a literal string. Using this setting
342 overrides C<processprefix> and C<nostatus>.
343  
344 =item sleep => \&hook
345  
346 If specified, &hook will be called instead of sleep(), with the time to sleep
347 in seconds as first argument and the Schedule::Cron object as second. This hook
348 allows you to use select() instead of sleep, so that you can handle IO, for
349 example job requests from a network connection.
350  
351 e.g.
352  
353 $cron->run( { sleep => \&sleep_hook, nofork => 1 } );
354  
355 sub sleep_hook {
356 my ($time, $cron) = @_;
357  
358 my ($rin, $win, $ein) = ('','','');
359 my ($rout, $wout, $eout);
360 vec($rin, fileno(STDIN), 1) = 1;
361 my ($nfound, $ttg) = select($rout=$rin, $wout=$win, $eout=$ein, $time);
362 if ($nfound) {
363 handle_io($rout, $wout, $eout);
364 }
365 return;
366 }
367  
368 =back
369  
370 =cut
371  
372 sub new
373 27 ▶{
Subroutine new: called CC=8 SCAR=21.1
Pod documented
374 27 my $class = shift;
375 27 ▶ my $dispatcher = shift || die "No dispatching sub provided";
Condition50%1/2
shift() || die('No dispatching sub provided')
l!l
270
MC/DC0%0/1
shift() || die('No dispatching sub provided')
shift()
Truth table50%1/2
A
A= shift()
Aresult
11
00
376 27 ▶ die "Dispatcher not a ref to a subroutine" unless ref($dispatcher) eq "CODE";
Branch: 1 branch
BranchTrueFalseTotal
unless ref $dispatcher eq "CODE" 0 27 27
377 27 ▶ my $cfg = ref($_[0]) eq "HASH" ? $_[0] : { @_ };
Branch: 1 branch
BranchTrueFalseTotal
ref $_[0] eq 'HASH' ? : 6 21 27
378 27 ▶ $cfg->{processprefix} = "Schedule::Cron" unless $cfg->{processprefix};
Branch: 1 branch
BranchTrueFalseTotal
unless $cfg->{"processprefix"} 24 3 27
379 27 ▶ my $timeshift = $cfg->{timeshift} || 0;
Condition100%2/2
$cfg->{'timeshift'} || 0
l!l
126
MC/DC100%1/1
$cfg->{'timeshift'} || 0
$cfg->{'timeshift'}
Truth table100%2/2
A
A= $cfg->{'timeshift'}
Aresult
11
00
380 27 my $self = {
381 cfg => $cfg,
382 dispatcher => $dispatcher,
383 timeshift => $timeshift,
384 queue => [ ],
385 map => { }
386 };
387 27 ▶ bless $self,(ref($class) || $class);
Condition33%1/3
ref $class || $class
l!l&&r!l&&!r
0270
MC/DC0%0/2
ref $class || $class
ref $class $class
Truth table33%1/3
A || B
A= ref $classB= $class
ABresult
1X1
011
000
388
389 27 ▶ $self->load_crontab if $cfg->{file};
Branch: 1 branch
BranchTrueFalseTotal
if $cfg->{"file"} 1 26 27
390 27 $self;
391 }
392  
393 =item $cron->load_crontab($file)
394  
395 =item $cron->load_crontab(file=>$file,[eval=>1])
396  
397 Loads and parses the crontab file C<$file>. The entries found in this file will
398 be B<added> to the current time table with C<$cron-E<gt>add_entry>.
399  
400 The format of the file consists of cron commands containing of lines with at
401 least 5 columns, whereas the first 5 columns specify the date. The rest of the
402 line (i.e columns 6 and greater) contains the argument with which the
403 dispatcher subroutine will be called. By default, the dispatcher will be
404 called with one single string argument containing the rest of the line
405 literally. Alternatively, if you call this method with the optional argument
406 C<eval=E<gt>1> (you must then use the second format shown above), the rest of
407 the line will be evaled before used as argument for the dispatcher.
408  
409 For the format of the first 5 columns, please see L<"add_entry">.
410  
411 Blank lines and lines starting with a C<#> will be ignored.
412  
413 There's no way to specify another subroutine within the crontab file. All
414 calls will be made to the dispatcher provided at construction time.
415  
416 If you want to start up fresh, you should call
417 C<$cron-E<gt>clean_timetable()> before.
418  
419 Example of a crontab fiqw(le:)
420  
421 # The following line runs on every Monday at 2:34 am
422 34 2 * * Mon "make_stats"
423 # The next line should be best read in with an eval=>1 argument
424 * * 1 1 * { NEW_YEAR => '1',HEADACHE => 'on' }
425  
426 =cut
427  
428 #'
429  
430 sub load_crontab
431 5 ▶{
Subroutine load_crontab: called CC=14 SCAR=26.5
Pod documented
432 5 my $self = shift;
433 5 my $cfg = shift;
434  
435 5 ▶ if ($cfg)
Branch: 1 branch
BranchTrueFalseTotal
if ($cfg) 4 1 5
436 {
437 4 ▶ if (@_)
Branch: 2 branches
BranchTrueFalseTotal
if (@_) { } 1 3 4
elsif (not ref $cfg) { } 2 1 3
438 {
439 1 ▶ $cfg = ref($cfg) eq "HASH" ? $cfg : { $cfg,@_ };
Branch: 1 branch
BranchTrueFalseTotal
ref $cfg eq 'HASH' ? : 0 1 1
440 }
441 elsif (!ref($cfg))
442 {
443 2 my $new_cfg = { };
444 2 $new_cfg->{file} = $cfg;
445 2 $cfg = $new_cfg;
446 }
447 }
448
449 5 ▶ my $file = $cfg->{file} || $self->{cfg}->{file} || die "No filename provided";
Condition60%3/5
$cfg->{'file'} || $self->{'cfg'}{'file'} || die('No filename provided')
l!l
50
$cfg->{"file"} or $self->{"cfg"}{"file"}
l!l&&r!l&&!r
410
MC/DC0%0/2
$cfg->{'file'} || $self->{'cfg'}{'file'} || die('No filename provided')
$cfg->{"file"} $self->{"cfg"}{"file"}
Truth table66%2/3
A or B
A= $cfg->{"file"}B= $self->{"cfg"}{"file"}
ABresult
1X1
011
000
450 5 ▶ my $eval = $cfg->{eval} || $self->{cfg}->{eval};
Condition100%3/3
$cfg->{'eval'} || $self->{'cfg'}{'eval'}
l!l&&r!l&&!r
212
MC/DC100%2/2
$cfg->{'eval'} || $self->{'cfg'}{'eval'}
$cfg->{'eval'} $self->{'cfg'}{'eval'}
Truth table100%3/3
A || B
A= $cfg->{'eval'}B= $self->{'cfg'}{'eval'}
ABresult
1X1
011
000
451
452 5 ▶ open(F,$file) || die "Cannot open schedule $file : $!";
Branch: 1 branch
BranchTrueFalseTotal
open F, $file or die "Cannot open schedule $file : $!" 5 0 5
453 5 my $line = 0;
454 5 ▶ while (<F>)
Branch: 1 branch
BranchTrueFalseTotal
if (defined($_ = readline F)) 345 5 350
455 {
456 345 $line++;
457 # Strip off trailing comments and ignore empty
458 # or pure comments lines:
459 345 s/#.*$//;
460 345 ▶ next if /^\s*$/;
Branch: 1 branch
BranchTrueFalseTotal
if /^\s*$/ 160 185 345
461 185 ▶ next if /^\s*#/;
Branch: 1 branch
BranchTrueFalseTotal
if /^\s*#/ 0 185 185
462 185 chomp;
463 185 s/\s*(.*)\s*$/$1/;
464 185 my ($min,$hour,$dmon,$month,$dweek,$rest) = split (/\s+/,$_,6);
465
466 185 my $time = [ $min,$hour,$dmon,$month,$dweek ];
467  
468 # Try to check, whether an optional 6th column specifying seconds
469 # exists:
470 185 my $args;
471 185 ▶ if ($rest)
Branch: 1 branch
BranchTrueFalseTotal
if ($rest) 185 0 185
472 {
473 185 my ($col6,$more_args) = split(/\s+/,$rest,2);
474 185 ▶ if ($col6 =~ /^[\d\-\*\,\/]+$/)
Branch: 1 branch
BranchTrueFalseTotal
if ($col6 =~ m[^[\d\-\*\,/]+$]) { } 15 170 185
475 {
476 15 push @$time,$col6;
477 15 dbg "M: $more_args";
478 15 $args = $more_args;
479 }
480 else
481 {
482 170 $args = $rest;
483 }
484 }
485 185 $self->add_entry($time,{ 'args' => $args, 'eval' => $eval});
486 }
487 5 close F;
488 }
489  
490 =item $cron->add_entry($timespec,[arguments])
491  
492 Adds a new entry to the list of scheduled cron jobs.
493  
494 B<Time and Date specification>
495  
496 C<$timespec> is the specification of the scheduled time in crontab format
497 (L<crontab(5)>) which contains five mandatory time and date fields and an
498 optional 6th column. C<$timespec> can be either a plain string, which contains
499 a whitespace separated time and date specification. Alternatively,
500 C<$timespec> can be a reference to an array containing the five elements for
501 the date fields.
502  
503 The time and date fields are (taken mostly from L<crontab(5)>, "Vixie" cron):
504  
505 field values
506 ===== ======
507 minute 0-59
508 hour 0-23
509 day of month 1-31
510 month 1-12 (or as names)
511 day of week 0-7 (0 or 7 is Sunday, or as names)
512 seconds 0-59 (optional)
513  
514 A field may be an asterisk (*), which always stands for
515 ``first-last''.
516  
517 Ranges of numbers are allowed. Ranges are two numbers
518 separated with a hyphen. The specified range is
519 inclusive. For example, 8-11 for an ``hours'' entry
520 specifies execution at hours 8, 9, 10 and 11.
521  
522 Lists are allowed. A list is a set of numbers (or
523 ranges) separated by commas. Examples: ``1,2,5,9'',
524 ``0-4,8-12''.
525  
526 Step values can be used in conjunction with ranges.
527 Following a range with ``/<number>'' specifies skips of
528 the numbers value through the range. For example,
529 ``0-23/2'' can be used in the hours field to specify
530 command execution every other hour (the alternative in
531 the V7 standard is ``0,2,4,6,8,10,12,14,16,18,20,22'').
532 Steps are also permitted after an asterisk, so if you
533 want to say ``every two hours'', just use ``*/2''.
534  
535 Names can also be used for the ``month'' and ``day of
536 week'' fields. Use the first three letters of the
537 particular day or month (case doesn't matter).
538  
539 Note: The day of a command's execution can be specified
540 by two fields -- day of month, and day of week.
541 If both fields are restricted (ie, aren't *), the
542 command will be run when either field matches the
543 current time. For example, ``30 4 1,15 * 5''
544 would cause a command to be run at 4:30 am on the
545 1st and 15th of each month, plus every Friday
546  
547 Examples:
548  
549 "8 0 * * *" ==> 8 minutes after midnight, every day
550 "5 11 * * Sat,Sun" ==> at 11:05 on each Saturday and Sunday
551 "0-59/5 * * * *" ==> every five minutes
552 "42 12 3 Feb Sat" ==> at 12:42 on 3rd of February and on
553 each Saturday in February
554 "32 11 * * * 0-30/2" ==> 11:32:00, 11:32:02, ... 11:32:30 every
555 day
556  
557 In addition, ranges or lists of names are allowed.
558  
559 An optional sixth column can be used to specify the seconds within the
560 minute. If not present, it is implicitly set to "0".
561  
562 B<Command specification>
563  
564 The subroutine to be executed when the C<$timespec> matches can be
565 specified in several ways.
566  
567 First, if the optional C<arguments> are lacking, the default dispatching
568 subroutine provided at construction time will be called without arguments.
569  
570 If the second parameter to this method is a reference to a subroutine, this
571 subroutine will be used instead of the dispatcher.
572  
573 Any additional parameters will be given as arguments to the subroutine to be
574 executed. You can also specify a reference to an array instead of a list of
575 parameters.
576  
577 You can also use a named parameter list provided as an hashref. The named
578 parameters recognized are:
579  
580 =over
581  
582 =item subroutine
583  
584 =item sub
585  
586 Reference to subroutine to be executed
587  
588 =item arguments
589  
590 =item args
591  
592 Reference to array containing arguments to be use when calling the subroutine
593  
594 =item eval
595  
596 If true, use the evaled string provided with the C<arguments> parameter. The
597 evaluation will take place immediately (not when the subroutine is going to be
598 called)
599  
600 =back
601  
602 Examples:
603  
604 $cron->add_entry("* * * * *");
605 $cron->add_entry("* * * * *","doit");
606 $cron->add_entry("* * * * *",\&dispatch,"first",2,"third");
607 $cron->add_entry("* * * * *",{'subroutine' => \&dispatch,
608 'arguments' => [ "first",2,"third" ]});
609 $cron->add_entry("* * * * *",{'subroutine' => \&dispatch,
610 'arguments' => '[ "first",2,"third" ]',
611 'eval' => 1});
612  
613 =cut
614  
615 sub add_entry
616 219 ▶{
Subroutine add_entry: called CC=19 SCAR=29.5
Pod documented
617 219 my $self = shift;
618 219 my $time = shift;
619 219 ▶ my $args = shift || [];
Condition100%2/2
shift() || []
l!l
20415
MC/DC100%1/1
shift() || []
shift()
Truth table100%2/2
A
A= shift()
Aresult
11
00
620 219 my $dispatch;
621
622 # dbg "Args: ",Dumper($time,$args);
623
624 219 ▶ if (ref($args) eq "HASH")
Branch: 2 branches
BranchTrueFalseTotal
if (ref $args eq 'HASH') { } 193 26 219
elsif (ref $args eq 'CODE') { } 4 22 26
625 {
626 193 my $cfg = $args;
627 193 $args = undef;
628 193 ▶ $dispatch = $cfg->{subroutine} || $cfg->{sub};
Condition66%2/3
$cfg->{'subroutine'} || $cfg->{'sub'}
l!l&&r!l&&!r
70186
MC/DC50%1/2
$cfg->{'subroutine'} || $cfg->{'sub'}
$cfg->{'subroutine'} $cfg->{'sub'}
Truth table66%2/3
A || B
A= $cfg->{'subroutine'}B= $cfg->{'sub'}
ABresult
1X1
011
000
629 193 ▶ $args = $cfg->{arguments} || $cfg->{args} || [];
Condition100%5/5
$cfg->{'arguments'} || $cfg->{'args'} || []
l!l
1876
$cfg->{"arguments"} or $cfg->{"args"}
l!l&&r!l&&!r
11866
MC/DC100%2/2
$cfg->{'arguments'} || $cfg->{'args'} || []
$cfg->{"arguments"} $cfg->{"args"}
Truth table100%3/3
A or B
A= $cfg->{"arguments"}B= $cfg->{"args"}
ABresult
1X1
011
000
630 193 ▶ if ($cfg->{eval} && $cfg)
Branch: 1 branch
BranchTrueFalseTotal
if ($cfg->{"eval"} and $cfg) 112 81 193
Condition66%2/3
$cfg->{"eval"} and $cfg
!ll&&!rl&&r
810112
MC/DC50%1/2
$cfg->{"eval"} and $cfg
$cfg->{"eval"} $cfg
Truth table66%2/3
A and B
A= $cfg->{"eval"}B= $cfg
ABresult
0X0
100
111
631 {
632 112 ▶ die "You have to provide a simple scalar if using eval" if (ref($args));
Branch: 1 branch
BranchTrueFalseTotal
if ref $args 1 111 112
633 111 my $orig_args = $args;
634 111 ▶ dbg "Evaled args ",Dumper($args) if $DEBUG;
Branch: 1 branch
BranchTrueFalseTotal
if $DEBUG 0 111 111
635 111 $args = [ eval $args ];
636 111 ▶ die "Cannot evaluate args (\"$orig_args\")"
Branch: 1 branch
BranchTrueFalseTotal
if $@ 0 111 111
637 if $@;
638 }
639 }
640 elsif (ref($args) eq "CODE")
641 {
642 4 $dispatch = $args;
643 4 ▶ $args = shift || [];
Condition50%1/2
shift() || []
l!l
04
MC/DC0%0/1
shift() || []
shift()
Truth table50%1/2
A
A= shift()
Aresult
11
00
644 }
645 218 ▶ if (ref($args) ne "ARRAY")
Branch: 1 branch
BranchTrueFalseTotal
if (ref $args ne "ARRAY") 81 137 218
646 {
647 81 $args = [ $args,@_ ];
648 }
649  
650 218 ▶ $dispatch ||= $self->{dispatcher};
Condition66%2/3
$dispatch ||= $self->{"dispatcher"}
l!l&&r!l&&!r
102080
MC/DC0%0/2
$dispatch ||= $self->{"dispatcher"}
$dispatch $self->{"dispatcher"}
Truth table66%2/3
A ||= B
A= $dispatchB= $self->{"dispatcher"}
ABresult
1X1
011
000
651  
652  
653 218 ▶ my $time_array = ref($time) ? $time : [ split(/\s+/,$time) ];
Branch: 1 branch
BranchTrueFalseTotal
ref $time ? : 185 33 218
654 218 ▶ die "Invalid number of columns in time entry (5 or 6)\n"
Branch: 1 branch
BranchTrueFalseTotal
if $time_array->$#* != 4 and $time_array->$#* != 5 1 217 218
Condition100%3/3
$time_array->$#* != 4 and $time_array->$#* != 5
!ll&&!rl&&r
172451
MC/DC100%2/2
$time_array->$#* != 4 and $time_array->$#* != 5
$time_array->$#* != 4 $time_array->$#* != 5
Truth table100%3/3
A and B
A= $time_array->$#* != 4B= $time_array->$#* != 5
ABresult
0X0
100
111
655 if ($#$time_array != 4 && $#$time_array !=5);
656 217 $time = join ' ',@$time_array;
657  
658 # dbg "Adding ",Dumper($time);
659 217 push @{$self->{time_table}},
660 {
661 time => $time,
662 dispatcher => $dispatch,
663 args => $args
664 };
665
666 217 $self->{entries_changed} = 1;
667 # dbg "Added Args ",Dumper($self->{args});
668
669 217 my $index = $#{$self->{time_table}};
670 217 my $id = $args->[0];
671 217 ▶ $self->{map}->{$id} = $index if $id;
Branch: 1 branch
BranchTrueFalseTotal
if $id 193 24 217
672
673 217 return $#{$self->{time_table}};
674 }
675  
676 =item @entries = $cron->list_entries()
677  
678 Return a list of cron entries. Each entry is a hash reference of the following
679 form:
680  
681 $entry = {
682 time => $timespec,
683 dispatch => $dispatcher,
684 args => $args_ref
685 }
686  
687 Here C<$timespec> is the specified time in crontab format as provided to
688 C<add_entry>, C<$dispatcher> is a reference to the dispatcher for this entry
689 and C<$args_ref> is a reference to an array holding additional arguments (which
690 can be an empty array reference). For further explanation of this arguments
691 refer to the documentation of the method C<add_entry>.
692  
693 The order index of each entry can be used within C<update_entry>, C<get_entry>
694 and C<delete_entry>. But be aware, when you are deleting an entry, that you
695 have to re-fetch the list, since the order will have changed.
696  
697 Note that these entries are returned by value and were obtained from the
698 internal list by a deep copy. I.e. you are free to modify it, but this won't
699 influence the original entries. Instead use C<update_entry> if you need to
700 modify an existing crontab entry.
701  
702 =cut
703  
704 sub list_entries
705 5 ▶{
Subroutine list_entries: called CC=2 SCAR=6.9
Pod documented
706 5 my ($self) = shift;
707
708 5 my @ret;
709 5 foreach my $entry (@{$self->{time_table}})
710 {
711 # Deep copy $entry
712 7 push @ret,$self->_deep_copy_entry($entry);
713 }
714 5 return @ret;
715 }
716  
717  
718 =item $entry = $cron->get_entry($idx)
719  
720 Get a single entry. C<$entry> is either a hashref with the possible keys
721 C<time>, C<dispatch> and C<args> (see C<list_entries()>) or undef if no entry
722 with the given index C<$idx> exists.
723  
724 =cut
725  
726 sub get_entry
727 91 ▶{
Subroutine get_entry: called CC=2 SCAR=6.9
Pod documented
728 91 my ($self,$idx) = @_;
729  
730 91 my $entry = $self->{time_table}->[$idx];
731 91 ▶ if ($entry)
Branch: 1 branch
BranchTrueFalseTotal
if ($entry) { } 90 1 91
732 {
733 90 return $self->_deep_copy_entry($entry);
734 }
735 else
736 {
737 1 return undef;
738 }
739 }
740  
741 =item $cron->delete_entry($idx)
742  
743 Delete the entry at index C<$idx>. Returns the deleted entry on success,
744 C<undef> otherwise.
745  
746 =cut
747  
748 sub delete_entry
749 3 ▶{
Subroutine delete_entry: called CC=5 SCAR=16.2
Pod documented
750 3 my ($self,$idx) = @_;
751  
752 3 ▶ if ($idx <= $#{$self->{time_table}})
Branch: 1 branch
BranchTrueFalseTotal
if ($idx <= $#{$$self{'time_table'};}) { } 3 0 3
753 {
754 3 $self->{entries_changed} = 1;
755  
756 # Remove entry from $self->{map} which
757 # remembers the index in the timetable by name (==id)
758 # and update all larger indexes appropriately
759 # Fix for #54692
760 3 my $map = $self->{map};
761 3 foreach my $key (keys %{$map}) {
762 6 ▶ if ($map->{$key} > $idx) {
Branch: 2 branches
BranchTrueFalseTotal
if ($map->{$key} > $idx) { } 2 4 6
elsif ($map->{$key} == $idx) { } 2 2 4
763 2 $map->{$key}--;
764 } elsif ($map->{$key} == $idx) {
765 2 delete $map->{$key};
766 }
767 }
768 3 return splice @{$self->{time_table}},$idx,1;
769 }
770 else
771 {
772 0 return undef;
773 }
774 }
775  
776 =item $cron->update_entry($idx,$entry)
777  
778 Updates the entry with index C<$idx>. C<$entry> is a hash ref as described in
779 C<list_entries()> and must contain at least a value C<$entry-E<gt>{time}>. If no
780 C<$entry-E<gt>{dispatcher}> is given, then the default dispatcher is used. This
781 method returns the old entry on success, C<undef> otherwise.
782  
783 =cut
784  
785 sub update_entry
786 1 ▶{
Subroutine update_entry: called CC=6 SCAR=19.2
Pod documented
787 1 my ($self,$idx,$entry) = @_;
788  
789 1 ▶ die "No update entry given" unless $entry;
Branch: 1 branch
BranchTrueFalseTotal
unless $entry 0 1 1
790 1 ▶ die "No time specification given" unless $entry->{time};
Branch: 1 branch
BranchTrueFalseTotal
unless $entry->{"time"} 0 1 1
791
792 1 ▶ if ($idx <= $#{$self->{time_table}})
Branch: 1 branch
BranchTrueFalseTotal
if ($idx <= $#{$$self{'time_table'};}) { } 1 0 1
793 {
794 1 my $new_entry = $self->_deep_copy_entry($entry);
795 $new_entry->{dispatcher} = $self->{dispatcher}
796 1 ▶ unless $new_entry->{dispatcher};
Branch: 1 branch
BranchTrueFalseTotal
unless $new_entry->{"dispatcher"} 1 0 1
797 $new_entry->{args} = []
798 1 ▶ unless $new_entry->{args};
Branch: 1 branch
BranchTrueFalseTotal
unless $new_entry->{"args"} 0 1 1
799 1 return splice @{$self->{time_table}},$idx,1,$new_entry;
800 }
801 else
802 {
803 0 return undef;
804 }
805 }
806  
807 =item $cron->run([options])
808  
809 This method starts the scheduler.
810  
811 When called without options, this method will never return and executes the
812 scheduled subroutine calls as needed.
813  
814 Alternatively, you can detach the main scheduler loop from the current process
815 (daemon mode). In this case, the pid of the forked scheduler process will be
816 returned.
817  
818 The C<options> parameter specifies the running mode of C<Schedule::Cron>. It
819 can be either a plain list which will be interpreted as a hash or it can be a
820 reference to a hash. The following named parameters (keys of the provided hash)
821 are recognized:
822  
823 =over
824  
825 =item detach
826  
827 If set to a true value the scheduler process is detached from the current
828 process (UNIX only).
829  
830 =item pid_file
831  
832 If running in daemon mode, name the optional file, in which the process id of
833 the scheduler process should be written. By default, no PID File will be
834 created.
835  
836 =item nofork, skip, catch, log, loglevel, nostatus, sleep
837  
838 See C<new()> for a description of these configuration parameters, which can be
839 provided here as well. Note, that the options given here overrides those of the
840 constructor.
841  
842 =back
843  
844  
845 Examples:
846  
847 # Start scheduler, detach from current process and
848 # write the PID of the forked scheduler to the
849 # specified file
850 $cron->run(detach=>1,pid_file=>"/var/run/scheduler.pid");
851  
852 # Start scheduler and wait forever.
853 $cron->run();
854  
855 =cut
856  
857 sub run
858 18 ▶{
Subroutine run: called CC=24 SCAR=46.2
Pod documented
859 18 my $self = shift;
860 18 ▶ my $cfg = ref($_[0]) eq "HASH" ? $_[0] : { @_ };
Branch: 1 branch
BranchTrueFalseTotal
ref $_[0] eq 'HASH' ? : 1 17 18
861 18 $cfg = { %{$self->{cfg}}, %$cfg }; # Merge in global config;
862  
863 18 my $log = $cfg->{log};
864 18 my $loglevel = $cfg->{loglevel};
865 18 ▶ $loglevel = 0 unless defined $loglevel;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $loglevel 18 0 18
866 18 my $sleeper = $cfg->{sleep};
867  
868 18 $self->_rebuild_queue;
869 18 delete $self->{entries_changed};
870 18 ▶ die "Nothing in schedule queue" unless @{$self->{queue}};
Branch: 1 branch
BranchTrueFalseTotal
unless @{$self->{"queue"};} 0 18 18
871
872 # Install reaper now.
873 18 ▶ unless ($cfg->{nofork}) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($cfg->{"nofork"}) 5 13 18
874 5 my $old_child_handler = $SIG{'CHLD'};
875 1 ▶ $SIG{'CHLD'} = sub {
Subroutine __ANON__: called CC=5 SCAR=18.1
876 1 ▶ dbg "Calling reaper" if $DEBUG;
Branch: 1 branch
BranchTrueFalseTotal
if $DEBUG 0 1 1
877 1 &REAPER();
878 1 ▶ if ($old_child_handler && ref $old_child_handler eq 'CODE')
Branch: 1 branch
BranchTrueFalseTotal
if ($old_child_handler and ref $old_child_handler eq "CODE") 1 0 1
Condition33%1/3
$old_child_handler and ref $old_child_handler eq "CODE"
!ll&&!rl&&r
001
MC/DC0%0/2
$old_child_handler and ref $old_child_handler eq "CODE"
$old_child_handler ref $old_child_handler eq "CODE"
Truth table33%1/3
A and B
A= $old_child_handlerB= ref $old_child_handler eq "CODE"
ABresult
0X0
100
111
879 {
880 1 ▶ dbg "Calling old child handler" if $DEBUG;
Branch: 1 branch
BranchTrueFalseTotal
if $DEBUG 0 1 1
881 #use B::Deparse ();
882 #my $deparse = B::Deparse->new;
883 #print 'sub ', $deparse->coderef2text($old_child_handler), "\n";
884 1 &$old_child_handler();
885 }
886 5 };
887 }
888
889 18 ▶ if (my $name = $cfg->{processname}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $name = $cfg->{"processname"}) 2 16 18
890 2 $0 = $name
891 }
892  
893 18 ▶ my $mainloop = sub {
Subroutine __ANON__: called CC=22 SCAR=35.2
894 MAIN:
895 18 while (42)
896 {
897 32 ▶ unless (@{$self->{queue}}) # Queue length
Branch: 1 branch
BranchTrueFalseTotal
unless (@{$self->{"queue"};}) 0 32 32
898 {
899 # Last job deleted itself, or we were run with no entries.
900 # We can't return, so throw an exception - perhaps someone will catch.
901 0 die "No more jobs to run\n";
902 }
903 32 my ($indexes,$time) = $self->_get_next_jobs();
904 32 ▶ dbg "Jobs for $time : ",join(",",@$indexes) if $DEBUG;
Branch: 1 branch
BranchTrueFalseTotal
if $DEBUG 0 32 32
905 32 my $now = $self->_now();
906 32 my $sleep = 0;
907 32 ▶ if ($time < $now)
Branch: 1 branch
BranchTrueFalseTotal
if ($time < $now) { } 1 31 32
908 {
909 1 ▶ if ($cfg->{skip})
Branch: 1 branch
BranchTrueFalseTotal
if ($cfg->{"skip"}) 1 0 1
910 {
911 1 for my $index (@$indexes) {
912 1 ▶ $log->(0,"Schedule::Cron - Skipping job $index")
Branch: 1 branch
BranchTrueFalseTotal
if $log and $loglevel <= 0 1 0 1
Condition33%1/3
$log and $loglevel <= 0
!ll&&!rl&&r
001
MC/DC0%0/2
$log and $loglevel <= 0
$log $loglevel <= 0
Truth table33%1/3
A and B
A= $logB= $loglevel <= 0
ABresult
0X0
100
111
913 if $log && $loglevel <= 0;
914 1 $self->_update_queue($index);
915 }
916 1 next;
917 }
918 # At least a safety airbag
919 0 $sleep = 1;
920 }
921 else
922 {
923 31 $sleep = $time - $now;
924 }
925  
926 31 ▶ unless ($cfg->{processname} || $cfg->{nostatus}) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($cfg->{"processname"} or $cfg->{"nostatus"}) 27 4 31
Condition100%3/3
$cfg->{"processname"} or $cfg->{"nostatus"}
l!l&&r!l&&!r
2227
MC/DC100%2/2
$cfg->{"processname"} or $cfg->{"nostatus"}
$cfg->{"processname"} $cfg->{"nostatus"}
Truth table100%3/3
A or B
A= $cfg->{"processname"}B= $cfg->{"nostatus"}
ABresult
1X1
011
000
927 27 $0 = $self->_get_process_prefix()." MainLoop - next: ".scalar(localtime($time));
928 }
929  
930 31 ▶ if (!$time) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($time) 0 31 31
931 0 ▶ die "Internal: No time found, self: ",$self->{queue},"\n" unless $time;
Branch: 1 branch
BranchTrueFalseTotal
unless $time 0 0 0
932 }
933  
934 31 ▶ dbg "R: sleep = $sleep | ",scalar(localtime($time))," (",scalar(localtime($now)),")" if $DEBUG;
Branch: 1 branch
BranchTrueFalseTotal
if $DEBUG 0 31 31
935  
936 31 ▶ while ($sleep > 0)
Branch: 1 branch
BranchTrueFalseTotal
if ($sleep > 0) 31 29 60
937 {
938 31 ▶ if ($sleeper)
Branch: 1 branch
BranchTrueFalseTotal
if ($sleeper) { } 0 31 31
939 {
940 0 $sleeper->($sleep,$self);
941 0 ▶ if ($self->{entries_changed})
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"entries_changed"}) 0 0 0
942 {
943 0 $self->_rebuild_queue;
944 0 delete $self->{entries_changed};
945 0 redo MAIN;
946 }
947 } else {
948 31 sleep($sleep);
949 }
950 29 $sleep = $time - $self->_now();
951 }
952  
953 29 for my $index (@$indexes) {
954 36 $self->_execute($index,$cfg);
955 # If "skip" is set and the job takes longer than a second, then
956 # the remaining jobs are skipped.
957 21 ▶ last if $cfg->{skip} && $time < $self->_now();
Branch: 1 branch
BranchTrueFalseTotal
if $cfg->{"skip"} and $time < $self->_now 1 20 21
Condition66%2/3
$cfg->{"skip"} and $time < $self->_now
!ll&&!rl&&r
2001
MC/DC50%1/2
$cfg->{"skip"} and $time < $self->_now
$cfg->{"skip"} $time < $self->_now
Truth table66%2/3
A and B
A= $cfg->{"skip"}B= $time < $self->_now
ABresult
0X0
100
111
958 }
959 14 $self->_cleanup_process_list($cfg);
960  
961 13 ▶ if ($self->{entries_changed}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{'entries_changed'}) { } 3 10 13
962 3 ▶ dbg "rebuilding queue" if $DEBUG;
Branch: 1 branch
BranchTrueFalseTotal
if $DEBUG 0 3 3
963 3 $self->_rebuild_queue;
964 3 delete $self->{entries_changed};
965 } else {
966 10 for my $index (@$indexes) {
967 14 $self->_update_queue($index);
968 }
969 }
970 }
971 18 };
972  
973 18 ▶ if ($cfg->{detach})
Branch: 1 branch
BranchTrueFalseTotal
if ($cfg->{'detach'}) { } 0 18 18
974 {
975 0 ▶ defined(my $pid = fork) or die "Can't fork: $!";
Branch: 1 branch
BranchTrueFalseTotal
defined(my $pid = fork) or die "Can't fork: $!" 0 0 0
976 0 ▶ if ($pid)
Branch: 1 branch
BranchTrueFalseTotal
if ($pid) { } 0 0 0
977 {
978 # Parent:
979 0 ▶ if ($cfg->{pid_file})
Branch: 1 branch
BranchTrueFalseTotal
if ($cfg->{"pid_file"}) 0 0 0
980 {
981 0 ▶ if (open(P,">".$cfg->{pid_file}))
Branch: 1 branch
BranchTrueFalseTotal
if (open P, '>' . $cfg->{'pid_file'}) { } 0 0 0
982 {
983 0 print P $pid,"\n";
984 0 close P;
985 }
986 else
987 {
988 0 warn "Warning: Cannot open ",$cfg->{pid_file}," : $!\n";
989 }
990
991 }
992 0 return $pid;
993 }
994 else
995 {
996 # Child:
997 # Try to detach from terminal:
998 0 chdir '/';
999 0 ▶ open STDIN, '/dev/null' or die "Can't read /dev/null: $!";
Branch: 1 branch
BranchTrueFalseTotal
open STDIN, "/dev/null" or die "Can't read /dev/null: $!" 0 0 0
1000 0 ▶ open STDOUT, '>/dev/null' or die "Can't write to /dev/null: $!";
Branch: 1 branch
BranchTrueFalseTotal
open STDOUT, ">/dev/null" or die "Can't write to /dev/null: $!" 0 0 0
1001
1002 0 eval { require POSIX; };
1003 0 ▶ if ($@)
Branch: 1 branch
BranchTrueFalseTotal
if ($@) { } 0 0 0
1004 {
1005 # if (1) {
1006 0 ▶ if (open(T,"/dev/tty"))
Branch: 1 branch
BranchTrueFalseTotal
if (open T, "/dev/tty") 0 0 0
1007 {
1008 0 dbg "No setsid found, trying ioctl() (Error: $@)";
1009 0 eval { require 'ioctl.ph'; };
1010 0 ▶ if ($@)
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 0 0 0
1011 {
1012 0 eval { require 'sys/ioctl.ph'; };
1013 0 ▶ if ($@)
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 0 0 0
1014 {
1015 0 die "No 'ioctl.ph'. Probably you have to run h2ph (Error: $@)";
1016 }
1017 }
1018 0 my $notty = &TIOCNOTTY;
1019 0 ▶ die "No TIOCNOTTY !" if $@ || !$notty;
Branch: 1 branch
BranchTrueFalseTotal
if $@ or not $notty 0 0 0
Condition0%0/3
$@ or not $notty
l!l&&r!l&&!r
000
MC/DC0%0/2
$@ or not $notty
$@ not $notty
Truth table0%0/3
A or not(B)
A= $@B= not $notty
ABresult
1X1
011
000
1020 0 ▶ ioctl(T,$notty,0) || die "Cannot issue ioctl(..,TIOCNOTTY) : $!";
Branch: 1 branch
BranchTrueFalseTotal
ioctl T, $notty, 0 or die "Cannot issue ioctl(..,TIOCNOTTY) : $!" 0 0 0
1021 0 close(T);
1022 };
1023 }
1024 else
1025 {
1026 0 ▶ &POSIX::setsid() || die "Can't start a new session: $!";
Branch: 1 branch
BranchTrueFalseTotal
&POSIX::setsid() or die "Can't start a new session: $!" 0 0 0
1027 }
1028 0 ▶ open STDERR, '>&STDOUT' or die "Can't dup stdout: $!";
Branch: 1 branch
BranchTrueFalseTotal
open STDERR, ">&STDOUT" or die "Can't dup stdout: $!" 0 0 0
1029
1030 0 ▶ unless ($cfg->{processname} || $cfg->{nostatus}) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($cfg->{"processname"} or $cfg->{"nostatus"}) 0 0 0
Condition0%0/3
$cfg->{"processname"} or $cfg->{"nostatus"}
l!l&&r!l&&!r
000
MC/DC0%0/2
$cfg->{"processname"} or $cfg->{"nostatus"}
$cfg->{"processname"} $cfg->{"nostatus"}
Truth table0%0/3
A or B
A= $cfg->{"processname"}B= $cfg->{"nostatus"}
ABresult
1X1
011
000
1031 0 $0 = $self->_get_process_prefix()." MainLoop";
1032 }
1033  
1034 0 &$mainloop();
1035 }
1036 }
1037 else
1038 {
1039 18 &$mainloop();
1040 }
1041 }
1042  
1043  
1044 =item $cron->clean_timetable()
1045  
1046 Remove all scheduled entries
1047  
1048 =cut
1049  
1050 sub clean_timetable
1051 2 ▶{
Subroutine clean_timetable: called CC=1 SCAR=0.0
Pod documented
1052 2 my $self = shift;
1053 2 $self->{entries_changed} = 1;
1054 2 $self->{time_table} = [];
1055 }
1056  
1057  
1058 =item $cron->check_entry($id)
1059  
1060 Check, whether the given ID is already registered in the timetable.
1061 A ID is the first argument in the argument parameter of the
1062 a crontab entry.
1063  
1064 Returns (one of) the index in the timetable (can be 0, too) if the ID
1065 could be found or C<undef> otherwise.
1066  
1067 Example:
1068  
1069 $cron->add_entry("* * * * *","ROTATE");
1070 .
1071 .
1072 defined($cron->check_entry("ROTATE")) || die "No ROTATE entry !"
1073  
1074 =cut
1075  
1076 sub check_entry
1077 4 ▶{
Subroutine check_entry: called CC=1 SCAR=0.0
Pod documented
1078 4 my $self = shift;
1079 4 my $id = shift;
1080 4 return $self->{map}->{$id};
1081 }
1082  
1083  
1084 =item $cron->get_next_execution_time($cron_entry,[$ref_time])
1085  
1086 Well, this is mostly an internal method, but it might be useful on
1087 its own.
1088  
1089 The purpose of this method is to calculate the next execution time
1090 from a specified crontab entry
1091  
1092 Parameters:
1093  
1094 =over
1095  
1096 =item $cron_entry
1097  
1098 The crontab entry as specified in L<"add_entry">
1099  
1100 =item $ref_time
1101  
1102 The reference time for which the next time should be searched which matches
1103 C<$cron_entry>. By default, take the current time
1104  
1105 =back
1106  
1107 This method returns the number of epoch-seconds of the next matched
1108 date for C<$cron_entry>.
1109  
1110 Since I suspect, that this calculation of the next execution time might
1111 fail in some circumstances (bugs are lurking everywhere ;-) an
1112 additional interactive method C<bug()> is provided for checking
1113 crontab entries against your expected output. Refer to the
1114 top-level README for additional usage information for this method.
1115  
1116 =cut
1117  
1118 sub get_next_execution_time
1119 100 ▶{
Subroutine get_next_execution_time: called CC=29 SCAR=35.0
Pod documented
1120 100 my $self = shift;
1121 100 my $cron_entry = shift;
1122 100 my $time = shift;
1123
1124 100 ▶ $cron_entry = [ split /\s+/,$cron_entry ] unless ref($cron_entry);
Branch: 1 branch
BranchTrueFalseTotal
unless ref $cron_entry 48 52 100
1125  
1126 # Expand and check entry:
1127 # =======================
1128 100 ▶ die "Exactly 5 or 6 columns has to be specified for a crontab entry ! (not ",
Branch: 1 branch
BranchTrueFalseTotal
if $cron_entry->$#* != 4 and $cron_entry->$#* != 5 0 100 100
Condition66%2/3
$cron_entry->$#* != 4 and $cron_entry->$#* != 5
!ll&&!rl&&r
46540
MC/DC0%0/2
$cron_entry->$#* != 4 and $cron_entry->$#* != 5
$cron_entry->$#* != 4 $cron_entry->$#* != 5
Truth table66%2/3
A and B
A= $cron_entry->$#* != 4B= $cron_entry->$#* != 5
ABresult
0X0
100
111
1129 scalar(@$cron_entry),")"
1130 if ($#$cron_entry != 4 && $#$cron_entry != 5);
1131
1132 100 my @expanded;
1133 my $w;
1134
1135 100 for my $i (0..$#$cron_entry)
1136 {
1137 554 my @e = split /,/,$cron_entry->[$i];
1138 554 my @res;
1139 my $t;
1140 554 ▶ while (defined($t = shift @e)) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined($t = shift @e)) 1375 554 1929
1141 # Subst "*/5" -> "0-59/5"
1142 1375 $t =~ s|^\*(/.+)$|$RANGES[$i][0]."-".$RANGES[$i][1].$1|e;
1143
1144 1375 ▶ if ($t =~ m|^([^-]+)-([^-/]+)(/(.*))?$|)
Branch: 1 branch
BranchTrueFalseTotal
if ($t =~ m[^([^-]+)-([^-/]+)(/(.*))?$]) { } 33 1342 1375
1145 {
1146 33 my ($low,$high,$step) = ($1,$2,$4);
1147 33 ▶ $step = 1 unless $step;
Branch: 1 branch
BranchTrueFalseTotal
unless $step 10 23 33
1148 33 ▶ if ($low !~ /^(\d+)/)
Branch: 1 branch
BranchTrueFalseTotal
unless ($low =~ /^(\d+)/) 7 26 33
1149 {
1150 7 $low = $ALPHACONV[$i]{lc $low};
1151 }
1152 33 ▶ if ($high !~ /^(\d+)/)
Branch: 1 branch
BranchTrueFalseTotal
unless ($high =~ /^(\d+)/) 7 26 33
1153 {
1154 7 $high = $ALPHACONV[$i]{lc $high};
1155 }
1156 33 ▶ if (! defined($low) || !defined($high) || $low > $high || $step !~ /^\d+$/)
Branch: 1 branch
BranchTrueFalseTotal
if (not defined $low && defined $high or $low > $high or not $step =~ /^\d+$/) 0 33 33
Condition33%3/9
not defined $low && defined $high or $low > $high or not $step =~ /^\d+$/
l!l&&r!l&&!r
0033
not defined $low && defined $high or $low > $high
l!l&&r!l&&!r
0033
defined $low && defined $high
!ll&&!rl&&r
0033
MC/DC0%0/4
not defined $low && defined $high or $low > $high or not $step =~ /^\d+$/
defined $low defined $high $low > $high not $step =~ /^\d+$/
Truth table20%1/5
not(A && B) or C or not(D)
A= defined $lowB= defined $highC= $low > $highD= not $step =~ /^\d+$/
ABCDresult
0XXX1
10XX1
111X1
11011
11000
1157 {
1158 0 die "Invalid cronentry '",$cron_entry->[$i],"'";
1159 }
1160 33 my $j;
1161 33 ▶ for ($j = $low; $j <= $high; $j += $step)
Branch: 1 branch
BranchTrueFalseTotal
if ($j <= $high) 771 33 804
1162 {
1163 771 push @e,$j;
1164 }
1165 }
1166 else
1167 {
1168 1342 ▶ $t = $ALPHACONV[$i]{lc $t} if $t !~ /^(\d+|\*)$/;
Branch: 1 branch
BranchTrueFalseTotal
unless $t =~ /^(\d+|\*)$/ 11 1331 1342
1169 1342 ▶ $t = $LOWMAP[$i]{$t} if( defined $t && exists($LOWMAP[$i]{$t}) );
Branch: 1 branch
BranchTrueFalseTotal
if defined $t and exists $LOWMAP[$i]{$t} 2 1340 1342
Condition66%2/3
defined $t and exists $LOWMAP[$i]{$t}
!ll&&!rl&&r
013402
MC/DC50%1/2
defined $t and exists $LOWMAP[$i]{$t}
defined $t exists $LOWMAP[$i]{$t}
Truth table66%2/3
A and B
A= defined $tB= exists $LOWMAP[$i]{$t}
ABresult
0X0
100
111
1170
1171 1342 ▶ die "Invalid cronentry '",$cron_entry->[$i],"'"
Branch: 1 branch
BranchTrueFalseTotal
if not defined $t or $t ne "*" and $t < $RANGES[$i][0] || $t > $RANGES[$i][1] 0 1342 1342
Condition44%4/9
not defined $t or $t ne "*" and $t < $RANGES[$i][0] || $t > $RANGES[$i][1]
l!l&&r!l&&!r
001342
$t ne "*" and $t < $RANGES[$i][0] || $t > $RANGES[$i][1]
!ll&&!rl&&r
4059370
$t < $RANGES[$i][0] or $t > $RANGES[$i][1]
l!l&&r!l&&!r
00937
MC/DC0%0/4
not defined $t or $t ne "*" and $t < $RANGES[$i][0] || $t > $RANGES[$i][1]
not defined $t $t ne "*" $t < $RANGES[$i][0] $t > $RANGES[$i][1]
Truth table40%2/5
not(A) or B and C or D
A= not defined $tB= $t ne "*"C= $t < $RANGES[$i][0]D= $t > $RANGES[$i][1]
ABCDresult
1XXX1
011X1
01011
00XX0
01000
1172 if (!defined($t) || ($t ne '*' && ($t < $RANGES[$i][0] || $t > $RANGES[$i][1])));
1173 1342 push @res,$t;
1174 }
1175 }
1176 554 ▶ push @expanded, ($#res == 0 && $res[0] eq '*') ? [ "*" ] : [ sort {$a <=> $b} @res];
Branch: 1 branch
BranchTrueFalseTotal
$#res == 0 && $res[0] eq '*' ? : 405 149 554
Condition100%3/3
$#res == 0 and $res[0] eq "*"
!ll&&!rl&&r
5495405
MC/DC100%2/2
$#res == 0 and $res[0] eq "*"
$#res == 0 $res[0] eq "*"
Truth table100%3/3
A and B
A= $#res == 0B= $res[0] eq "*"
ABresult
0X0
100
111
1177 }
1178
1179 # Check for strange bug
1180 100 $self->_verify_expanded_cron_entry($cron_entry,\@expanded);
1181  
1182 # Calculating time:
1183 # =================
1184 100 ▶ my $now = $time || time;
Condition100%2/2
$time || time
l!l
5248
MC/DC100%1/1
$time || time
$time
Truth table100%2/2
A
A= $time
Aresult
11
00
1185  
1186 100 ▶ if ($expanded[2]->[0] ne '*' && $expanded[4]->[0] ne '*')
Branch: 1 branch
BranchTrueFalseTotal
if ($expanded[2][0] ne '*' and $expanded[4][0] ne '*') { } 4 96 100
Condition100%3/3
$expanded[2][0] ne "*" and $expanded[4][0] ne "*"
!ll&&!rl&&r
81154
MC/DC100%2/2
$expanded[2][0] ne "*" and $expanded[4][0] ne "*"
$expanded[2][0] ne "*" $expanded[4][0] ne "*"
Truth table100%3/3
A and B
A= $expanded[2][0] ne "*"B= $expanded[4][0] ne "*"
ABresult
0X0
100
111
1187 {
1188 # Special check for which time is lower (Month-day or Week-day spec):
1189 4 my @bak = @{$expanded[4]};
1190 4 $expanded[4] = [ '*' ];
1191 4 my $t1 = $self->_calc_time($now,\@expanded);
1192 4 $expanded[4] = \@bak;
1193 4 $expanded[2] = [ '*' ];
1194 4 my $t2 = $self->_calc_time($now,\@expanded);
1195 4 ▶ dbg "MDay : ",scalar(localtime($t1))," -- WDay : ",scalar(localtime($t2)) if $DEBUG;
Branch: 1 branch
BranchTrueFalseTotal
if $DEBUG 0 4 4
1196 4 ▶ return $t1 < $t2 ? $t1 : $t2;
Branch: 1 branch
BranchTrueFalseTotal
$t1 < $t2 ? : 3 1 4
1197 }
1198 else
1199 {
1200 # No conflicts possible:
1201 96 return $self->_calc_time($now,\@expanded);
1202 }
1203 }
1204  
1205 =item $cron->set_timeshift($ts)
1206  
1207 Modify global time shift for all timetable. The timeshift is subbed from localtime
1208 to calculate next execution time for all scheduled jobs.
1209  
1210 ts parameter must be in seconds. Default value is 0. Negative values are allowed to
1211 shift time in the past.
1212  
1213 Returns actual timeshift in seconds.
1214  
1215 Example:
1216  
1217 $cron->set_timeshift(120);
1218  
1219 Will delay all jobs 2 minutes in the future.
1220  
1221 =cut
1222  
1223 sub set_timeshift
1224 0 ▶{
Subroutine set_timeshift: not called CC=2 SCAR=17.9
Pod documented
1225 0 my $self = shift;
1226 0 ▶ my $value = shift || 0;
Condition0%0/2
shift() || 0
l!l
00
MC/DC0%0/1
shift() || 0
shift()
Truth table0%0/2
A
A= shift()
Aresult
11
00
1227  
1228 0 $self->{timeshift} = $value;
1229 0 return $self->{timeshift};
1230 }
1231  
1232 # ==================================================
1233 # PRIVATE METHODS:
1234 # ==================================================
1235  
1236 # Build up executing queue and delete any
1237 # existing entries
1238 sub _rebuild_queue
1239 21 ▶{
Subroutine _rebuild_queue: called CC=2 SCAR=6.9
1240 21 my $self = shift;
1241 21 $self->{queue} = [ ];
1242 #dbg "TT: ",$#{$self->{time_table}};
1243 21 for my $id (0..$#{$self->{time_table}})
1244 {
1245 33 $self->_update_queue($id);
1246 }
1247 }
1248  
1249 # deeply copy an entry in the time table
1250 sub _deep_copy_entry
1251 98 ▶{
Subroutine _deep_copy_entry: called CC=1 SCAR=0.0
1252 98 my ($self,$entry) = @_;
1253  
1254 98 my $args = [ @{$entry->{args}} ];
1255 98 my $copied_entry = { %$entry };
1256 98 $copied_entry->{args} = $args;
1257 98 return $copied_entry;
1258 }
1259  
1260 # Return an array with an arrayref of entry index and the time which should be
1261 # executed now
1262 32 ▶sub _get_next_jobs {
Subroutine _get_next_jobs: called CC=3 SCAR=11.0
1263 32 my $self = shift;
1264 32 my ($index,$time) = @{shift @{$self->{queue}}};
1265 32 my $indexes = [ $index ];
1266 32 ▶ while (@{$self->{queue}} && $self->{queue}->[0]->[1] == $time) {
Branch: 1 branch
BranchTrueFalseTotal
if (@{$self->{"queue"};} and $self->{"queue"}[0][1] == $time) 9 32 41
Condition100%3/3
@{$self->{"queue"};} and $self->{"queue"}[0][1] == $time
!ll&&!rl&&r
2489
MC/DC100%2/2
@{$self->{"queue"};} and $self->{"queue"}[0][1] == $time
@{$self->{"queue"};} $self->{"queue"}[0][1] == $time
Truth table100%3/3
A and B
A= @{$self->{"queue"};}B= $self->{"queue"}[0][1] == $time
ABresult
0X0
100
111
1267 9 my $index = @{shift @{$self->{queue}}}[0];
1268 9 push @$indexes,$index;
1269 }
1270 32 return $indexes,$time;
1271 }
1272  
1273 # Execute a subroutine whose time has come
1274 sub _execute
1275 36 ▶{
Subroutine _execute: called CC=37 SCAR=42.3
1276 36 my $self = shift;
1277 36 my $index = shift;
1278 36 ▶ my $cfg = shift || $self->{cfg};
Condition33%1/3
shift() || $self->{'cfg'}
l!l&&r!l&&!r
3600
MC/DC0%0/2
shift() || $self->{'cfg'}
shift() $self->{'cfg'}
Truth table33%1/3
A || B
A= shift()B= $self->{'cfg'}
ABresult
1X1
011
000
1279 36 ▶ my $entry = $self->get_entry($index)
Condition50%1/2
$self->get_entry($index) || die("Internal: No entry with index $index found in ", Dumper([$self->list_entries]))
l!l
360
MC/DC0%0/1
$self->get_entry($index) || die("Internal: No entry with index $index found in ", Dumper([$self->list_entries]))
$self->get_entry($index)
Truth table50%1/2
A
A= $self->get_entry($index)
Aresult
11
00
1280 || die "Internal: No entry with index $index found in ",Dumper([$self->list_entries()]);
1281  
1282 36 my $pid;
1283  
1284  
1285 36 my $log = $cfg->{log};
1286 36 ▶ my $loglevel = $cfg->{loglevel} || 0;
Condition50%1/2
$cfg->{'loglevel'} || 0
l!l
036
MC/DC0%0/1
$cfg->{'loglevel'} || 0
$cfg->{'loglevel'}
Truth table50%1/2
A
A= $cfg->{'loglevel'}
Aresult
11
00
1287  
1288 36 ▶ unless ($cfg->{nofork})
Branch: 1 branch
BranchTrueFalseTotal
unless ($cfg->{"nofork"}) 7 29 36
1289 {
1290 7 ▶ if ($pid = fork)
Branch: 1 branch
BranchTrueFalseTotal
if ($pid = fork) 4 3 7
1291 {
1292 # Parent
1293 4 ▶ $log->(0,"Schedule::Cron - Forking child PID $pid") if $log && $loglevel <= 0;
Branch: 1 branch
BranchTrueFalseTotal
if $log and $loglevel <= 0 0 4 4
Condition33%1/3
$log and $loglevel <= 0
!ll&&!rl&&r
400
MC/DC0%0/2
$log and $loglevel <= 0
$log $loglevel <= 0
Truth table33%1/3
A and B
A= $logB= $loglevel <= 0
ABresult
0X0
100
111
1294 # Register PID
1295 4 $STARTEDCHILD{$pid} = 1;
1296 4 return;
1297 }
1298 }
1299
1300 # Child
1301 32 my $dispatch = $entry->{dispatcher};
1302 32 ▶ die "No subroutine provided with $dispatch"
Branch: 1 branch
BranchTrueFalseTotal
unless ref $dispatch eq "CODE" 0 32 32
1303 unless ref($dispatch) eq "CODE";
1304 32 my $args = $entry->{args};
1305
1306 32 my @args = ();
1307 32 ▶ if (defined($args) && defined($args->[0]))
Branch: 1 branch
BranchTrueFalseTotal
if (defined $args and defined $args->[0]) 3 29 32
Condition66%2/3
defined $args and defined $args->[0]
!ll&&!rl&&r
0293
MC/DC50%1/2
defined $args and defined $args->[0]
defined $args defined $args->[0]
Truth table66%2/3
A and B
A= defined $argsB= defined $args->[0]
ABresult
0X0
100
111
1308 {
1309 3 push @args,@$args;
1310 }
1311  
1312  
1313 32 ▶ if ($log && $loglevel <= 0 || !$cfg->{nofork} && !$cfg->{processname} && !$cfg->{nostatus}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($log and $loglevel <= 0 or not $cfg->{"nofork"} || $cfg->{"processname"} || $cfg->{"nostatus"}) 7 25 32
Condition75%9/12
$log and $loglevel <= 0 or not $cfg->{"nofork"} || $cfg->{"processname"} || $cfg->{"nostatus"}
l!l&&r!l&&!r
4325
$log and $loglevel <= 0
!ll&&!rl&&r
2804
$cfg->{'nofork'} || $cfg->{'processname'} || $cfg->{'nostatus'}
l!l&&r!l&&!r
2503
$cfg->{"nofork"} or $cfg->{"processname"}
l!l&&r!l&&!r
2503
MC/DC40%2/5
$log and $loglevel <= 0 or not $cfg->{"nofork"} || $cfg->{"processname"} || $cfg->{"nostatus"}
$log $loglevel <= 0 $cfg->{"nofork"} $cfg->{"processname"} $cfg->{'nostatus'}
Truth table33%3/9
A and B or not(C or D || E)
A= $logB= $loglevel <= 0C= $cfg->{"nofork"}D= $cfg->{"processname"}E= $cfg->{'nostatus'}
ABCDEresult
11XXX1
0X0001
100001
0X1XX0
0X01X0
0X0010
101XX0
1001X0
100010
1314 7 ▶ my $args_label = (@args && $loglevel <= -1) ? " with (".join(",",$self->_format_args(@args)).")" : "";
Branch: 1 branch
BranchTrueFalseTotal
@args && $loglevel <= -1 ? : 0 7 7
Condition66%2/3
@args and $loglevel <= -1
!ll&&!rl&&r
610
MC/DC0%0/2
@args and $loglevel <= -1
@args $loglevel <= -1
Truth table66%2/3
A and B
A= @argsB= $loglevel <= -1
ABresult
0X0
100
111
1315 $0 = $self->_get_process_prefix()." Dispatched job $index$args_label"
1316 7 ▶ unless $cfg->{nofork} || $cfg->{processname} || $cfg->{nostatus};
Branch: 1 branch
BranchTrueFalseTotal
unless $cfg->{"nofork"} or $cfg->{"processname"} or $cfg->{"nostatus"} 3 4 7
Condition66%4/6
$cfg->{"nofork"} or $cfg->{"processname"} or $cfg->{"nostatus"}
l!l&&r!l&&!r
403
$cfg->{"nofork"} or $cfg->{"processname"}
l!l&&r!l&&!r
403
MC/DC33%1/3
$cfg->{"nofork"} or $cfg->{"processname"} or $cfg->{"nostatus"}
$cfg->{"nofork"} $cfg->{"processname"} $cfg->{"nostatus"}
Truth table50%2/4
A or B or C
A= $cfg->{"nofork"}B= $cfg->{"processname"}C= $cfg->{"nostatus"}
ABCresult
1XX1
01X1
0011
0000
1317 7 ▶ $log->(0,"Schedule::Cron - Starting job $index$args_label")
Branch: 1 branch
BranchTrueFalseTotal
if $log and $loglevel <= 0 4 3 7
Condition66%2/3
$log and $loglevel <= 0
!ll&&!rl&&r
304
MC/DC50%1/2
$log and $loglevel <= 0
$log $loglevel <= 0
Truth table66%2/3
A and B
A= $logB= $loglevel <= 0
ABresult
0X0
100
111
1318 if $log && $loglevel <= 0;
1319 }
1320 32 my $dispatch_result;
1321 32 ▶ if ($cfg->{catch})
Branch: 1 branch
BranchTrueFalseTotal
if ($cfg->{'catch'}) { } 2 30 32
1322 {
1323 # Evaluate dispatcher
1324 eval
1325 2 {
1326 2 $dispatch_result = &$dispatch(@args);
1327 };
1328 2 ▶ if ($@)
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 2 0 2
1329 {
1330 2 ▶ $log->(2,"Schedule::Cron - Error within job $index: $@")
Branch: 1 branch
BranchTrueFalseTotal
if $log and $loglevel <= 2 2 0 2
Condition33%1/3
$log and $loglevel <= 2
!ll&&!rl&&r
002
MC/DC0%0/2
$log and $loglevel <= 2
$log $loglevel <= 2
Truth table33%1/3
A and B
A= $logB= $loglevel <= 2
ABresult
0X0
100
111
1331 if $log && $loglevel <= 2;
1332 }
1333 }
1334 else
1335 {
1336 # Let dispatcher die if needed.
1337 30 $dispatch_result = &$dispatch(@args);
1338 }
1339
1340 20 ▶ if($cfg->{after_job}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($cfg->{"after_job"}) 1 19 20
1341 1 my $job = $cfg->{after_job};
1342 1 ▶ if (ref($job) eq "CODE") {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $job eq 'CODE') { } 1 0 1
1343 eval
1344 1 {
1345 1 &$job($dispatch_result,@args);
1346 };
1347 1 ▶ if ($@)
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 0 1 1
1348 {
1349 0 ▶ $log->(2,"Schedule::Cron - Error while calling after_job callback with retval = $dispatch_result: $@")
Branch: 1 branch
BranchTrueFalseTotal
if $log and $loglevel <= 2 0 0 0
Condition0%0/3
$log and $loglevel <= 2
!ll&&!rl&&r
000
MC/DC0%0/2
$log and $loglevel <= 2
$log $loglevel <= 2
Truth table0%0/3
A and B
A= $logB= $loglevel <= 2
ABresult
0X0
100
111
1350 if $log && $loglevel <= 2;
1351 }
1352 } else {
1353 0 ▶ $log->(2,"Schedule::Cron - Invalid after_job callback, it's not a code ref (but ",$job,")")
Branch: 1 branch
BranchTrueFalseTotal
if $log and $loglevel <= 2 0 0 0
Condition0%0/3
$log and $loglevel <= 2
!ll&&!rl&&r
000
MC/DC0%0/2
$log and $loglevel <= 2
$log $loglevel <= 2
Truth table0%0/3
A and B
A= $logB= $loglevel <= 2
ABresult
0X0
100
111
1354 if $log && $loglevel <= 2;
1355 }
1356 }
1357  
1358 20 ▶ $log->(0,"Schedule::Cron - Finished job $index") if $log && $loglevel <= 0;
Branch: 1 branch
BranchTrueFalseTotal
if $log and $loglevel <= 0 3 17 20
Condition66%2/3
$log and $loglevel <= 0
!ll&&!rl&&r
1703
MC/DC50%1/2
$log and $loglevel <= 0
$log $loglevel <= 0
Truth table66%2/3
A and B
A= $logB= $loglevel <= 0
ABresult
0X0
100
111
1359 20 ▶ exit unless $cfg->{nofork};
Branch: 1 branch
BranchTrueFalseTotal
unless $cfg->{"nofork"} 3 17 20
1360 }
1361  
1362 # Update the scheduler queue with a new entry
1363 sub _update_queue
1364 48 ▶{
Subroutine _update_queue: called CC=5 SCAR=19.4
1365 48 my $self = shift;
1366 48 my $index = shift;
1367 48 my $entry = $self->get_entry($index);
1368
1369 48 my $new_time = $self->get_next_execution_time($entry->{time});
1370 # Check, whether next execution time is *smaller* than the current time.
1371 # This can happen during DST backflip:
1372 48 my $now = $self->_now();
1373 48 ▶ if ($new_time <= $now) {
Branch: 1 branch
BranchTrueFalseTotal
if ($new_time <= $now) 0 48 48
1374 0 ▶ dbg "Adjusting time calculation because of DST back flip (new_time - now = ",$new_time - $now,")" if $DEBUG;
Branch: 1 branch
BranchTrueFalseTotal
if $DEBUG 0 0 0
1375 # We are adding hours as long as our target time is in the future
1376 0 ▶ while ($new_time <= $now) {
Branch: 1 branch
BranchTrueFalseTotal
if ($new_time <= $now) 0 0 0
1377 0 $new_time += 3600;
1378 }
1379 }
1380  
1381 48 ▶ dbg "Updating Queue: ",scalar(localtime($new_time)) if $DEBUG;
Branch: 1 branch
BranchTrueFalseTotal
if $DEBUG 0 48 48
1382 48 $self->{queue} = [ sort { $a->[1] <=> $b->[1] } @{$self->{queue}},[$index,$new_time] ];
1383 #dbg "Queue now: ",Dumper($self->{queue});
1384 }
1385  
1386  
1387 # Out "now" which can be shifted if as argument
1388 110 ▶sub _now {
Subroutine _now: called CC=1 SCAR=0.0
1389 110 my $self = shift;
1390 110 return time + $self->{timeshift};
1391 }
1392  
1393 # The heart of the module.
1394 # calculate the next concrete date
1395 # for execution from a crontab entry
1396 sub _calc_time
1397 104 ▶{
Subroutine _calc_time: called CC=43 SCAR=38.2
1398 104 my $self = shift;
1399 104 my $now = shift;
1400 104 my $expanded = shift;
1401  
1402 104 ▶ my $offset = ($expanded->[5] ? 1 : 60) + $self->{timeshift};
Branch: 1 branch
BranchTrueFalseTotal
$expanded->[5] ? : 54 50 104
1403 104 my ($now_sec,$now_min,$now_hour,$now_mday,$now_mon,$now_wday,$now_year) =
1404 (localtime($now+$offset))[0,1,2,3,4,6,5];
1405 104 $now_mon++;
1406 104 $now_year += 1900;
1407  
1408 # Notes on variables set:
1409 # $now_... : the current date, fixed at call time
1410 # $dest_...: date used for backtracking. At the end, it contains
1411 # the desired lowest matching date
1412  
1413 104 my ($dest_mon,$dest_mday,$dest_wday,$dest_hour,$dest_min,$dest_sec,$dest_year) =
1414 ($now_mon,$now_mday,$now_wday,$now_hour,$now_min,$now_sec,$now_year);
1415  
1416 # dbg Dumper($expanded);
1417  
1418 # Airbag...
1419 104 ▶ while ($dest_year <= $now_year + 1)
Branch: 1 branch
BranchTrueFalseTotal
if ($dest_year <= $now_year + 1) 129 0 129
1420 {
1421 129 ▶ dbg "Parsing $dest_hour:$dest_min:$dest_sec $dest_year/$dest_mon/$dest_mday" if $DEBUG;
Branch: 1 branch
BranchTrueFalseTotal
if $DEBUG 0 129 129
1422
1423 # Check month:
1424 129 ▶ if ($expanded->[3]->[0] ne '*')
Branch: 1 branch
BranchTrueFalseTotal
if ($expanded->[3][0] ne "*") 21 108 129
1425 {
1426 21 ▶ unless (defined ($dest_mon = $self->_get_nearest($dest_mon,$expanded->[3])))
Branch: 1 branch
BranchTrueFalseTotal
unless (defined($dest_mon = $self->_get_nearest($dest_mon, $expanded->[3]))) 8 13 21
1427 {
1428 8 $dest_mon = $expanded->[3]->[0];
1429 8 $dest_year++;
1430 }
1431 }
1432
1433 # Check for day of month:
1434 129 ▶ if ($expanded->[2]->[0] ne '*')
Branch: 1 branch
BranchTrueFalseTotal
if ($expanded->[2][0] ne '*') { } 28 101 129
1435 {
1436 28 ▶ if ($dest_mon != $now_mon)
Branch: 1 branch
BranchTrueFalseTotal
if ($dest_mon != $now_mon) { } 12 16 28
1437 {
1438 12 $dest_mday = $expanded->[2]->[0];
1439 }
1440 else
1441 {
1442 16 ▶ unless (defined ($dest_mday = $self->_get_nearest($dest_mday,$expanded->[2])))
Branch: 1 branch
BranchTrueFalseTotal
unless (defined($dest_mday = $self->_get_nearest($dest_mday, $expanded->[2]))) 5 11 16
1443 {
1444 # Next day matched is within the next month. ==> redo it
1445 5 $dest_mday = $expanded->[2]->[0];
1446 5 $dest_mon++;
1447 5 ▶ if ($dest_mon > 12)
Branch: 1 branch
BranchTrueFalseTotal
if ($dest_mon > 12) 5 0 5
1448 {
1449 5 $dest_mon = 1;
1450 5 $dest_year++;
1451 }
1452 5 ▶ dbg "Backtrack mday: $dest_mday/$dest_mon/$dest_year" if $DEBUG;
Branch: 1 branch
BranchTrueFalseTotal
if $DEBUG 0 5 5
1453 5 next;
1454 }
1455 }
1456 }
1457 else
1458 {
1459 101 ▶ $dest_mday = ($dest_mon == $now_mon ? $dest_mday : 1);
Branch: 1 branch
BranchTrueFalseTotal
$dest_mon == $now_mon ? : 96 5 101
1460 }
1461
1462 # Check for day of week:
1463 124 ▶ if ($expanded->[4]->[0] ne '*')
Branch: 1 branch
BranchTrueFalseTotal
if ($expanded->[4][0] ne '*') { } 17 107 124
1464 {
1465 17 $dest_wday = $self->_get_nearest($dest_wday,$expanded->[4]);
1466 17 ▶ $dest_wday = $expanded->[4]->[0] unless $dest_wday;
Branch: 1 branch
BranchTrueFalseTotal
unless $dest_wday 7 10 17
1467
1468 17 my ($mon,$mday,$year);
1469 # dbg "M: $dest_mon MD: $dest_mday WD: $dest_wday Y:$dest_year";
1470 17 ▶ $dest_mday = 1 if $dest_mon != $now_mon;
Branch: 1 branch
BranchTrueFalseTotal
if $dest_mon != $now_mon 3 14 17
1471 17 my $t = parsedate(sprintf("%4.4d/%2.2d/%2.2d",$dest_year,$dest_mon,$dest_mday));
1472 17 ($mon,$mday,$year) =
1473 (localtime(parsedate("$WDAYS[$dest_wday]",PREFER_FUTURE=>1,NOW=>$t-1)))[4,3,5];
1474 17 $mon++;
1475 17 $year += 1900;
1476
1477 17 ▶ dbg "Calculated $mday/$mon/$year for weekday ",$WDAYS[$dest_wday] if $DEBUG;
Branch: 1 branch
BranchTrueFalseTotal
if $DEBUG 0 17 17
1478 17 ▶ if ($mon != $dest_mon || $year != $dest_year) {
Branch: 1 branch
BranchTrueFalseTotal
if ($mon != $dest_mon or $year != $dest_year) 3 14 17
Condition66%2/3
$mon != $dest_mon or $year != $dest_year
l!l&&r!l&&!r
3014
MC/DC50%1/2
$mon != $dest_mon or $year != $dest_year
$mon != $dest_mon $year != $dest_year
Truth table66%2/3
A or B
A= $mon != $dest_monB= $year != $dest_year
ABresult
1X1
011
000
1479 3 ▶ dbg "backtracking" if $DEBUG;
Branch: 1 branch
BranchTrueFalseTotal
if $DEBUG 0 3 3
1480 3 $dest_mon = $mon;
1481 3 $dest_year = $year;
1482 3 $dest_mday = 1;
1483 3 $dest_wday = (localtime(parsedate(sprintf("%4.4d/%2.2d/%2.2d",
1484 $dest_year,$dest_mon,$dest_mday))))[6];
1485 3 next;
1486 }
1487
1488 14 $dest_mday = $mday;
1489 }
1490 else
1491 {
1492 107 ▶ unless ($dest_mday)
Branch: 1 branch
BranchTrueFalseTotal
unless ($dest_mday) 0 107 107
1493 {
1494 0 ▶ $dest_mday = ($dest_mon == $now_mon ? $dest_mday : 1);
Branch: 1 branch
BranchTrueFalseTotal
$dest_mon == $now_mon ? : 0 0 0
1495 }
1496 }
1497  
1498
1499 # Check for hour
1500 121 ▶ if ($expanded->[1]->[0] ne '*')
Branch: 1 branch
BranchTrueFalseTotal
if ($expanded->[1][0] ne '*') { } 46 75 121
1501 {
1502 46 ▶ if ($dest_mday != $now_mday || $dest_mon != $now_mon || $dest_year != $now_year)
Branch: 1 branch
BranchTrueFalseTotal
if ($dest_mday != $now_mday or $dest_mon != $now_mon or $dest_year != $now_year) { } 27 19 46
Condition83%5/6
$dest_mday != $now_mday or $dest_mon != $now_mon or $dest_year != $now_year
l!l&&r!l&&!r
27019
$dest_mday != $now_mday or $dest_mon != $now_mon
l!l&&r!l&&!r
24319
MC/DC66%2/3
$dest_mday != $now_mday or $dest_mon != $now_mon or $dest_year != $now_year
$dest_mday != $now_mday $dest_mon != $now_mon $dest_year != $now_year
Truth table75%3/4
A or B or C
A= $dest_mday != $now_mdayB= $dest_mon != $now_monC= $dest_year != $now_year
ABCresult
1XX1
01X1
0011
0000
1503 {
1504 27 $dest_hour = $expanded->[1]->[0];
1505 }
1506 else
1507 {
1508 #dbg "Checking for next hour $dest_hour";
1509 19 ▶ unless (defined ($dest_hour = $self->_get_nearest($dest_hour,$expanded->[1])))
Branch: 1 branch
BranchTrueFalseTotal
unless (defined($dest_hour = $self->_get_nearest($dest_hour, $expanded->[1]))) 8 11 19
1510 {
1511 # Hour to match is at the next day ==> redo it
1512 8 $dest_hour = $expanded->[1]->[0];
1513 8 my $t = parsedate(sprintf("%2.2d:%2.2d:%2.2d %4.4d/%2.2d/%2.2d",
1514 $dest_hour,$dest_min,$dest_sec,$dest_year,$dest_mon,$dest_mday));
1515 8 ($dest_mday,$dest_mon,$dest_year,$dest_wday) =
1516 (localtime(parsedate("+ 1 day",NOW=>$t)))[3,4,5,6];
1517 8 $dest_mon++;
1518 8 $dest_year += 1900;
1519 8 next;
1520 }
1521 }
1522 }
1523 else
1524 {
1525 75 ▶ $dest_hour = ($dest_mday == $now_mday ? $dest_hour : 0);
Branch: 1 branch
BranchTrueFalseTotal
$dest_mday == $now_mday ? : 72 3 75
1526 }
1527 # Check for minute
1528 113 ▶ if ($expanded->[0]->[0] ne '*')
Branch: 1 branch
BranchTrueFalseTotal
if ($expanded->[0][0] ne '*') { } 38 75 113
1529 {
1530 38 ▶ if ($dest_hour != $now_hour || $dest_mday != $now_mday || $dest_mon != $dest_mon || $dest_year != $now_year)
Branch: 1 branch
BranchTrueFalseTotal
if ($dest_hour != $now_hour or $dest_mday != $now_mday or $dest_mon != $dest_mon or $dest_year != $now_year) { } 30 8 38
Condition77%7/9
$dest_hour != $now_hour or $dest_mday != $now_mday or $dest_mon != $dest_mon or $dest_year != $now_year
l!l&&r!l&&!r
3008
$dest_hour != $now_hour or $dest_mday != $now_mday or $dest_mon != $dest_mon
l!l&&r!l&&!r
3008
$dest_hour != $now_hour or $dest_mday != $now_mday
l!l&&r!l&&!r
2738
MC/DC50%2/4
$dest_hour != $now_hour or $dest_mday != $now_mday or $dest_mon != $dest_mon or $dest_year != $now_year
$dest_hour != $now_hour $dest_mday != $now_mday $dest_mon != $dest_mon $dest_year != $now_year
Truth table60%3/5
A or B or C or D
A= $dest_hour != $now_hourB= $dest_mday != $now_mdayC= $dest_mon != $dest_monD= $dest_year != $now_year
ABCDresult
1XXX1
01XX1
001X1
00011
00000
1531 {
1532 30 $dest_min = $expanded->[0]->[0];
1533 }
1534 else
1535 {
1536 8 ▶ unless (defined ($dest_min = $self->_get_nearest($dest_min,$expanded->[0])))
Branch: 1 branch
BranchTrueFalseTotal
unless (defined($dest_min = $self->_get_nearest($dest_min, $expanded->[0]))) 1 7 8
1537 {
1538 # Minute to match is at the next hour ==> redo it
1539 1 $dest_min = $expanded->[0]->[0];
1540 1 my $t = parsedate(sprintf("%2.2d:%2.2d:%2.2d %4.4d/%2.2d/%2.2d",
1541 $dest_hour,$dest_min,$dest_sec,$dest_year,$dest_mon,$dest_mday));
1542 1 ($dest_hour,$dest_mday,$dest_mon,$dest_year,$dest_wday) =
1543 (localtime(parsedate(" + 1 hour",NOW=>$t))) [2,3,4,5,6];
1544 1 $dest_mon++;
1545 1 $dest_year += 1900;
1546 1 next;
1547 }
1548 }
1549 }
1550 else
1551 {
1552 75 ▶ if ($dest_hour != $now_hour ||
Branch: 1 branch
BranchTrueFalseTotal
if ($dest_hour != $now_hour or $dest_mday != $now_mday or $dest_year != $now_year) 9 66 75
Condition83%5/6
$dest_hour != $now_hour or $dest_mday != $now_mday or $dest_year != $now_year
l!l&&r!l&&!r
9066
$dest_hour != $now_hour or $dest_mday != $now_mday
l!l&&r!l&&!r
8166
MC/DC66%2/3
$dest_hour != $now_hour or $dest_mday != $now_mday or $dest_year != $now_year
$dest_hour != $now_hour $dest_mday != $now_mday $dest_year != $now_year
Truth table75%3/4
A or B or C
A= $dest_hour != $now_hourB= $dest_mday != $now_mdayC= $dest_year != $now_year
ABCresult
1XX1
01X1
0011
0000
1553 $dest_mday != $now_mday ||
1554 $dest_year != $now_year) {
1555 9 $dest_min = 0;
1556 }
1557 }
1558 # Check for seconds
1559 112 ▶ if ($expanded->[5])
Branch: 1 branch
BranchTrueFalseTotal
if ($expanded->[5]) { } 61 51 112
1560 {
1561 61 ▶ if ($expanded->[5]->[0] ne '*')
Branch: 1 branch
BranchTrueFalseTotal
if ($expanded->[5][0] ne '*') { } 45 16 61
1562 {
1563 45 ▶ if ($dest_min != $now_min)
Branch: 1 branch
BranchTrueFalseTotal
if ($dest_min != $now_min) { } 7 38 45
1564 {
1565 7 $dest_sec = $expanded->[5]->[0];
1566 }
1567 else
1568 {
1569 38 ▶ unless (defined ($dest_sec = $self->_get_nearest($dest_sec,$expanded->[5])))
Branch: 1 branch
BranchTrueFalseTotal
unless (defined($dest_sec = $self->_get_nearest($dest_sec, $expanded->[5]))) 7 31 38
1570 {
1571 # Second to match is at the next minute ==> redo it
1572 7 $dest_sec = $expanded->[5]->[0];
1573 7 my $t = parsedate(sprintf("%2.2d:%2.2d:%2.2d %4.4d/%2.2d/%2.2d",
1574 $dest_hour,$dest_min,$dest_sec,
1575 $dest_year,$dest_mon,$dest_mday));
1576 7 ($dest_min,$dest_hour,$dest_mday,$dest_mon,$dest_year,$dest_wday) =
1577 (localtime(parsedate(" + 1 minute",NOW=>$t))) [1,2,3,4,5,6];
1578 7 $dest_mon++;
1579 7 $dest_year += 1900;
1580 7 next;
1581 }
1582 }
1583 }
1584 else
1585 {
1586 16 ▶ $dest_sec = ($dest_min == $now_min ? $dest_sec : 0);
Branch: 1 branch
BranchTrueFalseTotal
$dest_min == $now_min ? : 16 0 16
1587 }
1588 }
1589 else
1590 {
1591 51 $dest_sec = 0;
1592 }
1593
1594 # We did it !!
1595 105 my $date = sprintf("%2.2d:%2.2d:%2.2d %4.4d/%2.2d/%2.2d",
1596 $dest_hour,$dest_min,$dest_sec,$dest_year,$dest_mon,$dest_mday);
1597 105 ▶ dbg "Next execution time: $date ",$WDAYS[$dest_wday] if $DEBUG;
Branch: 1 branch
BranchTrueFalseTotal
if $DEBUG 0 105 105
1598 105 my $result = parsedate($date, VALIDATE => 1);
1599 # Check for a valid date
1600 105 ▶ if ($result)
Branch: 1 branch
BranchTrueFalseTotal
if ($result) { } 104 1 105
1601 {
1602 # Valid date... return it!
1603 104 return $result;
1604 }
1605 else
1606 {
1607 # Invalid date i.e. (02/30/2008). Retry it with another, possibly
1608 # valid date
1609 1 my $t = parsedate($date); # print scalar(localtime($t)),"\n";
1610 1 ($dest_hour,$dest_mday,$dest_mon,$dest_year,$dest_wday) =
1611 (localtime(parsedate(" + 1 second",NOW=>$t))) [2,3,4,5,6];
1612 1 $dest_mon++;
1613 1 $dest_year += 1900;
1614 1 next;
1615 }
1616 }
1617  
1618 # Die with an error because we couldn't find a next execution entry
1619 0 my $dumper = new Data::Dumper($expanded);
1620 0 $dumper->Terse(1);
1621 0 $dumper->Indent(0);
1622  
1623 0 die "No suitable next execution time found for ",$dumper->Dump(),", now == ",scalar(localtime($now)),"\n";
1624 }
1625  
1626 # get next entry in list or
1627 # undef if is the highest entry found
1628 sub _get_nearest
1629 119 ▶{
Subroutine _get_nearest: called CC=3 SCAR=11.0
1630 119 my $self = shift;
1631 119 my $x = shift;
1632 119 my $to_check = shift;
1633 119 foreach my $i (0 .. $#$to_check)
1634 {
1635 443 ▶ if ($$to_check[$i] >= $x)
Branch: 1 branch
BranchTrueFalseTotal
if ($to_check->[$i] >= $x) 83 360 443
1636 {
1637 83 return $$to_check[$i] ;
1638 }
1639 }
1640 36 return undef;
1641 }
1642  
1643  
1644 # prepare a list of object for pretty printing e.g. in the process list
1645 1 ▶sub _format_args {
Subroutine _format_args: called CC=1 SCAR=0.0
1646 1 my $self = shift;
1647 1 my @args = @_;
1648 1 my $dumper = new Data::Dumper(\@args);
1649 1 $dumper->Terse(1);
1650 1 $dumper->Maxdepth(2);
1651 1 $dumper->Indent(0);
1652 1 return $dumper->Dump();
1653 }
1654  
1655 # get the prefix to use when setting $0
1656 30 ▶sub _get_process_prefix {
Subroutine _get_process_prefix: called CC=2 SCAR=7.1
1657 30 my $self = shift;
1658 30 ▶ my $prefix = $self->{cfg}->{processprefix} || "Schedule::Cron";
Condition50%1/2
$self->{'cfg'}{'processprefix'} || 'Schedule::Cron'
l!l
300
MC/DC0%0/1
$self->{'cfg'}{'processprefix'} || 'Schedule::Cron'
$self->{'cfg'}{'processprefix'}
Truth table50%1/2
A
A= $self->{'cfg'}{'processprefix'}
Aresult
11
00
1659 30 return $prefix;
1660 }
1661  
1662 # our very own debugging routine
1663 # ('guess everybody has its own style ;-)
1664 # Callers check $DEBUG on the critical path to save the computes
1665 # used to produce expensive arguments. Omitting those would be
1666 # functionally correct, but rather wasteful.
1667 sub dbg
1668 15 ▶{
Subroutine dbg: called CC=5 SCAR=31.0
1669 15 ▶ if ($DEBUG)
Branch: 1 branch
BranchTrueFalseTotal
if ($DEBUG) 0 15 15
1670 {
1671 0 ▶ my $args = join('',@_) || "";
Condition0%0/2
join('', @_) || ''
l!l
00
MC/DC0%0/1
join('', @_) || ''
join('', @_)
Truth table0%0/2
A
A= join('', @_)
Aresult
11
00
1672 0 my $caller = (caller(1))[0];
1673 0 my $line = (caller(0))[2];
1674 0 ▶ $caller ||= $0;
Condition0%0/3
$caller ||= $0
l!l&&r!l&&!r
000
MC/DC0%0/2
$caller ||= $0
$caller $0
Truth table0%0/3
A ||= B
A= $callerB= $0
ABresult
1X1
011
000
1675 0 ▶ if (length $caller > 22)
Branch: 1 branch
BranchTrueFalseTotal
if (length $caller > 22) 0 0 0
1676 {
1677 0 $caller = substr($caller,0,10)."..".substr($caller,-10,10);
1678 }
1679 0 print STDERR sprintf ("%02d:%02d:%02d [%22.22s %4.4s] %s\n",
1680 (localtime)[2,1,0],$caller,$line,$args);
1681 }
1682 }
1683  
1684 # Helper method for reporting bugs concerning calculation
1685 # of execution bug:
1686 18 *bug = \&report_exectime_bug; # Shortcut
1687 sub report_exectime_bug
1688 0 ▶{
Subroutine report_exectime_bug: not called CC=16 SCAR=56.1
Pod undocumented
1689 0 my $self = shift;
1690 0 my $endless = shift;
1691 0 my $time = time;
1692 0 my $inp;
1693 0 my $now = $self->_time_as_string($time);
1694 0 my $email;
1695  
1696 do
1697 0 ▶ {
Branch: 1 branch
BranchTrueFalseTotal
$endless and do { do { while (1) { $inp = $self->_get_input("Reference time\n(default: $now) : "); if ($inp) { parsedate($inp) or print qq[Couldn't parse "$inp"\n], next; $now = $inp; } ; last; } ; my $now_time = parsedate($now); my($next_time, $next); my @entries; while (1) { $inp = $self->_get_input("Crontab time (5 columns) : "); @entries = split(/\s+/, $inp, 0); if (@entries != 5) { print qq[Invalid crontab entry "$inp"\n]; next; } ; eval { do { local $SIG{"ALRM"} = sub { die "TIMEOUT"; } ; alarm 60; $next_time = "Schedule::Cron"->get_next_execution_time(\@entries, $now_time); alarm 0 } }; if ($@) { alarm 0; if ($@ eq "TIMEOUT") { $next_time = -1; } else { print qq[Invalid crontab entry "$inp" ($@)\n]; next; } ; } ; if ($next_time > 0) { $next = $self->_time_as_string($next_time); } else { $next = "Run into infinite loop !!"; } ; last; } ; my($expected, $expected_time); while (1) { $inp = $self->_get_input("Expected time : "); unless ($expected_time = parsedate($inp)) { print qq[Couldn't parse "$inp"\n]; next; } ; $expected = $self->_time_as_string($expected_time); last; } ; if ($expected eq $next) { print "\nHmm, seems that everything's ok, or ?\n\n"; print "Calculated time: ", $next, "\n"; print "Expected time : ", $expected, "\n"; } else { print "Congratulation, you hit a bug. \n\n"; $email = $self->_get_input("Your E-Mail Address (if available) : ") unless defined $email; $email = "" unless defined $email; print "\n", "================================================================================", "\n"; print "Please report the following lines\nto roland\@cpan.org\n\n"; print "# ", "------------------------------------------------------------------------------", "\n"; print "Reftime: ", $now, "\n"; print "# Reported by : ", $email, "\n" if $email; printf "%8s %8s %8s %8s %8s %s\n", @entries, $expected; print "# Calculated : \n"; printf "# %8s %8s %8s %8s %8s %s\n", @entries, $next; unless ($endless) { require Config; my $vers = `uname -r 2>/dev/null` || $Config::Config{"osvers"}; chomp $vers; my $osname = `uname -s 2>/dev/null` || $Config::Config{"osname"}; chomp $osname; print "# OS: $osname ($vers)\n"; print "# Perl-Version: $]\n"; print "# Time::ParseDate-Version: ", $Time::ParseDate::VERSION, "\n"; } ; print "# ", "------------------------------------------------------------------------------", "\n"; } ; print "\n", "================================================================================", "\n" } } 0 0 0
1698 0 while (1)
1699 {
1700 0 $inp = $self->_get_input("Reference time\n(default: $now) : ");
1701 0 ▶ if ($inp)
Branch: 1 branch
BranchTrueFalseTotal
if ($inp) 0 0 0
1702 {
1703 0 ▶ parsedate($inp) || (print "Couldn't parse \"$inp\"\n",next);
Branch: 1 branch
BranchTrueFalseTotal
parsedate($inp) or print qq[Couldn't parse "$inp"\n], next 0 0 0
1704 0 $now = $inp;
1705 }
1706 0 last;
1707 }
1708 0 my $now_time = parsedate($now);
1709
1710 0 my ($next_time,$next);
1711 0 my @entries;
1712 0 while (1)
1713 {
1714 0 $inp = $self->_get_input("Crontab time (5 columns) : ");
1715 0 @entries = split (/\s+/,$inp);
1716 0 ▶ if (@entries != 5)
Branch: 1 branch
BranchTrueFalseTotal
if (@entries != 5) 0 0 0
1717 {
1718 0 print "Invalid crontab entry \"$inp\"\n";
1719 0 next;
1720 }
1721 eval
1722 0 {
1723 0 ▶ local $SIG{ALRM} = sub { die "TIMEOUT" };
Subroutine __ANON__: not called CC=1 SCAR=6.9
1724 0 alarm(60);
1725 0 $next_time = Schedule::Cron->get_next_execution_time(\@entries,$now_time);
1726 0 alarm(0);
1727 };
1728 0 ▶ if ($@)
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 0 0 0
1729 {
1730 0 alarm(0);
1731 0 ▶ if ($@ eq "TIMEOUT")
Branch: 1 branch
BranchTrueFalseTotal
if ($@ eq 'TIMEOUT') { } 0 0 0
1732 {
1733 0 $next_time = -1;
1734 } else
1735 {
1736 0 print "Invalid crontab entry \"$inp\" ($@)\n";
1737 0 next;
1738 }
1739 }
1740
1741 0 ▶ if ($next_time > 0)
Branch: 1 branch
BranchTrueFalseTotal
if ($next_time > 0) { } 0 0 0
1742 {
1743 0 $next = $self->_time_as_string($next_time);
1744 } else
1745 {
1746 0 $next = "Run into infinite loop !!";
1747 }
1748 0 last;
1749 }
1750
1751 0 my ($expected,$expected_time);
1752 0 while (1)
1753 {
1754 0 $inp = $self->_get_input("Expected time : ");
1755 0 ▶ unless ($expected_time = parsedate($inp))
Branch: 1 branch
BranchTrueFalseTotal
unless ($expected_time = parsedate($inp)) 0 0 0
1756 {
1757 0 print "Couldn't parse \"$inp\"\n";
1758 0 next;
1759 }
1760 0 $expected = $self->_time_as_string($expected_time);
1761 0 last;
1762 }
1763
1764 # Print out bug report:
1765 0 ▶ if ($expected eq $next)
Branch: 1 branch
BranchTrueFalseTotal
if ($expected eq $next) { } 0 0 0
1766 {
1767 0 print "\nHmm, seems that everything's ok, or ?\n\n";
1768 0 print "Calculated time: ",$next,"\n";
1769 0 print "Expected time : ",$expected,"\n";
1770 } else
1771 {
1772 0 print <<EOT;
1773 Congratulation, you hit a bug.
1774  
1775 EOT
1776 0 ▶ $email = $self->_get_input("Your E-Mail Address (if available) : ")
Branch: 1 branch
BranchTrueFalseTotal
unless defined $email 0 0 0
1777 unless defined($email);
1778 0 ▶ $email = "" unless defined($email);
Branch: 1 branch
BranchTrueFalseTotal
unless defined $email 0 0 0
1779
1780 0 print "\n","=" x 80,"\n";
1781 0 print <<EOT;
1782 Please report the following lines
1783 to roland\@cpan.org
1784  
1785 EOT
1786 0 print "# ","-" x 78,"\n";
1787 0 print "Reftime: ",$now,"\n";
1788 0 ▶ print "# Reported by : ",$email,"\n" if $email;
Branch: 1 branch
BranchTrueFalseTotal
if $email 0 0 0
1789 0 printf "%8s %8s %8s %8s %8s %s\n",@entries,$expected;
1790 0 print "# Calculated : \n";
1791 0 printf "# %8s %8s %8s %8s %8s %s\n",@entries,$next;
1792 0 ▶ unless ($endless)
Branch: 1 branch
BranchTrueFalseTotal
unless ($endless) 0 0 0
1793 {
1794 0 require Config;
1795 0 ▶ my $vers = `uname -r 2>/dev/null` || $Config::Config{'osvers'} ;
Condition0%0/3
`uname -r 2>/dev/null` || $Config::Config{'osvers'}
l!l&&r!l&&!r
000
MC/DC0%0/2
`uname -r 2>/dev/null` || $Config::Config{'osvers'}
`uname -r 2>/dev/null` $Config::Config{'osvers'}
Truth table0%0/3
A || B
A= `uname -r 2>/dev/null`B= $Config::Config{'osvers'}
ABresult
1X1
011
000
1796 0 chomp $vers;
1797 0 ▶ my $osname = `uname -s 2>/dev/null` || $Config::Config{'osname'};
Condition0%0/3
`uname -s 2>/dev/null` || $Config::Config{'osname'}
l!l&&r!l&&!r
000
MC/DC0%0/2
`uname -s 2>/dev/null` || $Config::Config{'osname'}
`uname -s 2>/dev/null` $Config::Config{'osname'}
Truth table0%0/3
A || B
A= `uname -s 2>/dev/null`B= $Config::Config{'osname'}
ABresult
1X1
011
000
1798 0 chomp $osname;
1799 0 print "# OS: $osname ($vers)\n";
1800 0 print "# Perl-Version: $]\n";
1801 0 print "# Time::ParseDate-Version: ",$Time::ParseDate::VERSION,"\n";
1802 }
1803 0 print "# ","-" x 78,"\n";
1804 }
1805
1806 0 print "\n","=" x 80,"\n";
1807 } while ($endless);
1808 }
1809  
1810 18 my ($input_initialized,$term);
1811 sub _get_input
1812 0 ▶{
Subroutine _get_input: not called CC=6 SCAR=35.0
1813 0 my $self = shift;
1814 0 my $prompt = shift;
1815 18 ▶ use vars qw($term);
Subroutine BEGIN: called CC=1 SCAR=0.0
1816  
1817 0 ▶ unless (defined($input_initialized))
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $input_initialized) 0 0 0
1818 {
1819 0 eval { require Term::ReadLine; };
1820
1821 0 ▶ $input_initialized = $@ ? 0 : 1;
Branch: 1 branch
BranchTrueFalseTotal
$@ ? : 0 0 0
1822 0 ▶ if ($input_initialized)
Branch: 1 branch
BranchTrueFalseTotal
if ($input_initialized) 0 0 0
1823 {
1824 0 $term = new Term::ReadLine;
1825 0 $term->ornaments(0);
1826 }
1827 }
1828
1829 0 ▶ unless ($input_initialized)
Branch: 1 branch
BranchTrueFalseTotal
if ($input_initialized) { } 0 0 0
1830 {
1831 0 print $prompt;
1832 0 my $inp = <STDIN>;
1833 0 chomp $inp;
1834 0 return $inp;
1835 }
1836 else
1837 {
1838 0 chomp $prompt;
1839 0 my @prompt = split /\n/s,$prompt;
1840 0 ▶ if ($#prompt > 0)
Branch: 1 branch
BranchTrueFalseTotal
if ($#prompt > 0) 0 0 0
1841 {
1842 0 print join "\n",@prompt[0..$#prompt-1],"\n";
1843 }
1844 0 my $inp = $term->readline($prompt[$#prompt]);
1845 0 return $inp;
1846 }
1847 }
1848  
1849 sub _time_as_string
1850 0 ▶{
Subroutine _time_as_string: not called CC=1 SCAR=6.9
1851 0 my $self = shift;
1852 0 my $time = shift;
1853  
1854 0 my ($min,$hour,$mday,$month,$year,$wday) = (localtime($time))[1..6];
1855 0 $month++;
1856 0 $year += 1900;
1857 0 $wday = $WDAYS[$wday];
1858 0 return sprintf("%2.2d:%2.2d %2.2d/%2.2d/%4.4d %s",
1859 $hour,$min,$mday,$month,$year,$wday);
1860 }
1861  
1862  
1863 # As reported by RT Ticket #24712 sometimes,
1864 # the expanded version of the cron entry is flaky.
1865 # However, this occurs only very rarely and randomly.
1866 # So, we need to provide good diagnostics when this
1867 # happens
1868 100 ▶sub _verify_expanded_cron_entry {
Subroutine _verify_expanded_cron_entry: called CC=4 SCAR=14.1
1869 100 my $self = shift;
1870 100 my $original = shift;
1871 100 my $entry = shift;
1872 100 ▶ die "Internal: Not an array ref. Orig: ",Dumper($original), ", expanded: ",Dumper($entry)," (self = ",Dumper($self),")"
Branch: 1 branch
BranchTrueFalseTotal
unless ref $entry eq "ARRAY" 0 100 100
1873 unless ref($entry) eq "ARRAY";
1874
1875 100 for my $i (0 .. $#{$entry}) {
1876 554 ▶ die "Internal: Part $i of entry is not an array ref. Original: ",
Branch: 1 branch
BranchTrueFalseTotal
unless ref $entry->[$i] eq "ARRAY" 0 554 554
1877 Dumper($original),", expanded: ",Dumper($entry)," (self=",Dumper($self),")",
1878 unless ref($entry->[$i]) eq "ARRAY";
1879 }
1880 }
1881  
1882 =back
1883  
1884 =head1 DST ISSUES
1885  
1886 Daylight saving occurs typically twice a year: In the first switch, one hour is
1887 skipped. Any job which triggers in this skipped hour will be fired in the
1888 next hour. So, when the DST switch goes from 2:00 to 3:00 a job which is
1889 scheduled for 2:43 will be executed at 3:43.
1890  
1891 For the reverse backwards switch later in the year, the behavior is
1892 undefined. Two possible behaviors can occur: For jobs triggered in short
1893 intervals, where the next execution time would fire in the extra hour as well,
1894 the job could be executed again or skipped in this extra hour. Currently,
1895 running C<Schedule::Cron> in C<MET> would skip the extra job, in C<PST8PDT> it
1896 would execute a second time. The reason is the way how L<Time::ParseDate>
1897 calculates epoch times for dates given like C<02:50:00 2009/10/25>. Should it
1898 return the seconds since 1970 for this time happening 'first', or for this time
1899 in the extra hour ? As it turns out, L<Time::ParseDate> returns the epoch time
1900 of the first occurrence for C<PST8PDT> and for C<MET> it returns the second
1901 occurrence. Unfortunately, there is no way to specify I<which> entry
1902 L<Time::ParseDate> should pick (until now). Of course, after all, this is
1903 obviously not L<Time::ParseDate>'s fault, since a simple date specification
1904 within the DST back-switch period B<is> ambiguous. However, it would be nice if
1905 the parsing behavior of L<Time::ParseDate> would be consistent across time
1906 zones (a ticket has be raised for fixing this). Then L<Schedule::Cron>'s
1907 behavior within a DST backward switch would be consistent as well.
1908  
1909 Since changing the internal algorithm which worked now for over ten years would
1910 be too risky and I don't see any simple solution for this right now, it is
1911 likely that this I<undefined> behavior will exist for some time. Maybe some
1912 hero is coming along and will fix this, but this is probably not me ;-)
1913  
1914 Sorry for that.
1915  
1916 =head1 AUTHORS
1917  
1918 Roland Huß <roland@consol.de>
1919  
1920 Currently maintained by Nicholas Hubbard <nicholashubbard@posteo.net>
1921  
1922 =head1 CONTRIBUTORS
1923  
1924 =over 4
1925  
1926 =item *
1927  
1928 Alexandr Ciornii <alexchorny@gmail.com>
1929  
1930 =item *
1931  
1932 Andrew Danforth
1933  
1934 =item *
1935  
1936 Andy Ford
1937  
1938 =item *
1939  
1940 Bray Jones
1941  
1942 =item *
1943  
1944 Clinton Gormley
1945  
1946 =item *
1947  
1948 Eric Wilhelm
1949  
1950 =item *
1951  
1952 Frank Mayer
1953  
1954 =item *
1955  
1956 Jamie McCarthy
1957  
1958 =item *
1959  
1960 Loic Paillotin
1961  
1962 =item *
1963  
1964 Nicholas Hubbard <nicholashubbard@posteo.net>
1965  
1966 =item *
1967  
1968 Peter Vary
1969  
1970 =item *
1971  
1972 Philippe Verdret
1973  
1974 =back
1975  
1976 =head1 COPYRIGHT AND LICENSE
1977  
1978 Copyright (c) 1999-2013 Roland Huß.
1979  
1980 Copyright (c) 2022-2023 Nicholas Hubbard.
1981  
1982 This library is free software; you can redistribute it and/or
1983 modify it under the same terms as Perl itself.
1984  
1985 =cut
1986  
1987 18 1;
↑ Summary