1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Hhxsv5\LaravelS\Swoole\Timer; |
4
|
|
|
|
5
|
|
|
use Swoole\Http\Server; |
6
|
|
|
use Swoole\Process; |
7
|
|
|
use Swoole\Timer; |
8
|
|
|
|
9
|
|
|
trait TimerTrait |
10
|
|
|
{ |
11
|
|
|
public function addTimerProcess(Server $swoole, array $config, array $laravelConfig) |
12
|
|
|
{ |
13
|
|
|
if (empty($config['enable']) || empty($config['jobs'])) { |
14
|
|
|
return; |
15
|
|
|
} |
16
|
|
|
|
17
|
|
|
$startTimer = function (Process $process) use ($swoole, $config, $laravelConfig) { |
18
|
|
|
$pidfile = dirname($swoole->setting['pid_file']) . '/laravels-timer-process.pid'; |
19
|
|
|
file_put_contents($pidfile, $process->pid); |
20
|
|
|
$this->setProcessTitle(sprintf('%s laravels: timer process', $config['process_prefix'])); |
|
|
|
|
21
|
|
|
$this->initLaravel($laravelConfig, $swoole); |
|
|
|
|
22
|
|
|
$timerIds = []; |
23
|
|
|
foreach ($config['jobs'] as $jobClass) { |
24
|
|
|
if (is_array($jobClass) && isset($jobClass[0])) { |
25
|
|
|
$job = new $jobClass[0](isset($jobClass[1]) ? $jobClass[1] : []); |
26
|
|
|
} else { |
27
|
|
|
$job = new $jobClass(); |
28
|
|
|
} |
29
|
|
|
if (!($job instanceof CronJob)) { |
30
|
|
|
throw new \InvalidArgumentException(sprintf( |
31
|
|
|
'%s must extend the abstract class %s', |
32
|
|
|
get_class($job), |
33
|
|
|
CronJob::class |
34
|
|
|
) |
35
|
|
|
); |
36
|
|
|
} |
37
|
|
|
if (empty($job->interval())) { |
38
|
|
|
throw new \InvalidArgumentException(sprintf('The interval of %s cannot be empty', get_class($job))); |
39
|
|
|
} |
40
|
|
|
$runProcess = function () use ($job) { |
41
|
|
|
$runCallback = function () use ($job) { |
42
|
|
|
$this->callWithCatchException(function () use ($job) { |
|
|
|
|
43
|
|
|
$job->run(); |
44
|
|
|
}); |
45
|
|
|
}; |
46
|
|
|
class_exists('Swoole\Coroutine') ? go($runCallback) : $runCallback(); |
47
|
|
|
}; |
48
|
|
|
|
49
|
|
|
$timerId = Timer::tick($job->interval(), $runProcess); |
50
|
|
|
$timerIds[] = $timerId; |
51
|
|
|
$job->setTimerId($timerId); |
52
|
|
|
if ($job->isImmediate()) { |
53
|
|
|
Timer::after(1, $runProcess); |
54
|
|
|
} |
55
|
|
|
} |
56
|
|
|
|
57
|
|
|
Process::signal(SIGUSR1, function ($signo) use ($config, $timerIds, $process) { |
|
|
|
|
58
|
|
|
foreach ($timerIds as $timerId) { |
59
|
|
|
Timer::clear($timerId); |
60
|
|
|
} |
61
|
|
|
Timer::after($config['max_wait_time'] * 1000, function () use ($process) { |
62
|
|
|
$process->exit(0); |
63
|
|
|
}); |
64
|
|
|
}); |
65
|
|
|
}; |
66
|
|
|
|
67
|
|
|
$timerProcess = new Process($startTimer, false, false); |
68
|
|
|
if ($swoole->addProcess($timerProcess)) { |
|
|
|
|
69
|
|
|
return $timerProcess; |
70
|
|
|
} |
71
|
|
|
} |
72
|
|
|
} |