1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace cvweiss\projectbase; |
4
|
|
|
|
5
|
|
|
class Job |
6
|
|
|
{ |
7
|
|
|
public static function doJobs($timeout = 60):bool |
8
|
|
|
{ |
9
|
|
|
self::addJobs(); |
10
|
|
|
$maxChildren = Config::getInstance()->get("maxJobChildren", 20); |
11
|
|
|
|
12
|
|
|
$time = time() + $timeout; |
13
|
|
|
$redis = Redis::get(); |
14
|
|
|
$queueJobs = new JobQueue($redis); |
15
|
|
|
$children = []; |
16
|
|
|
|
17
|
|
|
while (time() <= $time) { |
18
|
|
|
$job = $queueJobs->pop(); |
19
|
|
|
|
20
|
|
|
$pid = ($job === null) ? 0 : pcntl_fork(); |
21
|
|
|
if ($job !== null && $pid === 0) return self::runJob($job); |
22
|
|
|
$children[$pid] = true; |
23
|
|
|
self::checkChildren($maxChildren, $children); |
24
|
|
|
} |
25
|
|
|
return false; |
26
|
|
|
} |
27
|
|
|
|
28
|
|
|
private static function checkChildren(int $maxChildren, array &$children) |
29
|
|
|
{ |
30
|
|
|
while (count($children) > $maxChildren) { |
31
|
|
|
$status = null; |
32
|
|
|
$pidDone = pcntl_waitpid(0, $status); |
33
|
|
|
unset($children[$pidDone]); |
34
|
|
|
} |
35
|
|
|
} |
36
|
|
|
|
37
|
|
|
|
38
|
|
|
private static function runJob($job):bool |
39
|
|
|
{ |
40
|
|
|
if ($job !== null) { |
41
|
|
|
$class = new $job['class']; |
42
|
|
|
$function = $job['function']; |
43
|
|
|
\cli_set_process_title('php cron.php ' . $job['class'] . '->' . $function); |
44
|
|
|
$args = $job['args']; |
45
|
|
|
$class->$function($args); |
46
|
|
|
} |
47
|
|
|
|
48
|
|
|
return true; |
49
|
|
|
} |
50
|
|
|
|
51
|
|
|
public static function addJobs() |
52
|
|
|
{ |
53
|
|
|
if (Redis::canRun(__CLASS__) === false) return; |
54
|
|
|
|
55
|
|
|
$jobs = Config::getInstance()->get("cronjobs", []); |
56
|
|
|
foreach ($jobs as $className) { |
57
|
|
|
self::checkClass('\\' . $className); |
58
|
|
|
} |
59
|
|
|
} |
60
|
|
|
|
61
|
|
|
private static function checkClass($className) |
62
|
|
|
{ |
63
|
|
|
$class = new $className(); |
64
|
|
|
|
65
|
|
|
if (!($class instanceof CronJob)) throw new IllegalException("$className is not an instanceof \\cvweiss\projectbase\\CronJob"); |
66
|
|
|
|
67
|
|
|
$cron = \Cron\CronExpression::factory($class->getCron()); |
68
|
|
|
if ($cron->isDue() && get_class($class) != basename(__CLASS__)) { |
69
|
|
|
self::addJob($className, 'execute', []); |
70
|
|
|
} |
71
|
|
|
} |
72
|
|
|
|
73
|
|
|
public static function addJob(string $className, string $function, array $args = [], int $priority = 0) |
74
|
|
|
{ |
75
|
|
|
$redis = Redis::get(); |
76
|
|
|
$queueJobs = new JobQueue($redis); |
77
|
|
|
$job = ['class' => $className, 'function' => $function, 'args' => $args]; |
78
|
|
|
$queueJobs->push($job, $priority); |
79
|
|
|
} |
80
|
|
|
} |
81
|
|
|
|
82
|
|
|
|