-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathJob.php
91 lines (81 loc) · 2.3 KB
/
Job.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
<?php
/**
* CronJobberPhp (http://github.com/CoreyLoose/CronJobberPhp)
*
* Licensed under The Clear BSD License
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright 2011, Corey Losenegger (http://coreyloose.com)
* @license Clear BSD (http://labs.metacarta.com/license-explanation.html)
*/
class libs_CronJobberPhp_Job
{
const SECONDS_MOD_H = '* 60 * 60';
const SECONDS_MOD_M = '* 60';
public $timeStr;
public $cmd;
public $hash;
public function __construct( $timeStr, $cmd, $hash )
{
$this->timeStr = $timeStr;
$this->cmd = $cmd;
$this->hash = $hash;
}
public function runAsync()
{
$asyncCmd =
'php '.dirname(__FILE__).'/run_job_async.php '.
$this->timeStr.' "'.
$this->cmd.'" '.
$this->hash; //.' &> /dev/null &';
echo $asyncCmd."\n";
exec($asyncCmd);
}
public function exec()
{
exec($this->cmd);
}
public function shouldRunNow( $lastRun )
{
echo 'getNextRun('.$this->timeStr.', '.$lastRun.') = '.
$this->getNextRun($this->timeStr, $lastRun)."\n";
if( $this->getNextRun($this->timeStr, $lastRun) <= 0 ) {
return TRUE;
}
return FALSE;
}
public function getNextRun( $timeStr, $lastRun, $currentTime = null )
{
if( $currentTime === null ) {
$currentTime = time();
}
if( $lastRun > $currentTime ) {
throw new Exception('Command cannot have been run in the future.');
}
if( preg_match('/[0-9]{2}:[0-9]{2}:[0-9]{2}/', $timeStr) ) {
$todayRun = strtotime(date('Y-m-d', $currentTime).' '.$timeStr);
$tomorrowRun = strtotime(date('Y-m-d', $currentTime+60*60*24).' '.$timeStr);
if( $currentTime > $todayRun && $todayRun > $lastRun ) {
return $todayRun - $currentTime;
}
if( $currentTime < $todayRun ) {
return $todayRun - $currentTime;
}
return $tomorrowRun - $currentTime;
}
else if( preg_match('/[0-9]+[M|H|m|h]/', $timeStr) ) {
$number = (int)substr($timeStr, 0, strlen($timeStr)-1);
$letter = strtolower(substr($timeStr, -1));
//Turn H or M into a multiplication statement and eval it
$letterMod = self::SECONDS_MOD_M;
if( $letter == 'h' ) {
$letterMod = self::SECONDS_MOD_H;
}
eval('$secondsMod = '.$number.$letterMod.';');
return ($currentTime - $lastRun - $secondsMod) * -1;
}
else {
throw new Exception("Unknown time format '".$timeStr."'");
}
}
}