1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Hhxsv5\LaravelS\Swoole\Traits; |
4
|
|
|
|
5
|
|
|
use Hhxsv5\LaravelS\Swoole\Timer\CronJob; |
6
|
|
|
|
7
|
|
|
trait TimerTrait |
8
|
|
|
{ |
9
|
|
|
use ProcessTitleTrait; |
10
|
|
|
use LaravelTrait; |
11
|
|
|
use LogTrait; |
12
|
|
|
|
13
|
|
|
public function addTimerProcess(\swoole_server $swoole, array $config, array $laravelConfig) |
14
|
|
|
{ |
15
|
|
|
if (empty($config['enable']) || empty($config['jobs'])) { |
16
|
|
|
return; |
17
|
|
|
} |
18
|
|
|
|
19
|
|
|
$startTimer = function (\swoole_process $process) use ($swoole, $config, $laravelConfig) { |
20
|
|
|
file_put_contents($config['pid_file'], $process->pid); |
21
|
|
|
$this->setProcessTitle(sprintf('%s laravels: timer process', $config['process_prefix'])); |
22
|
|
|
$this->initLaravel($laravelConfig, $swoole); |
23
|
|
|
$timerIds = []; |
24
|
|
|
foreach ($config['jobs'] as $jobClass) { |
25
|
|
|
if (is_array($jobClass) && isset($jobClass[0])) { |
26
|
|
|
$job = new $jobClass[0](isset($jobClass[1]) ? $jobClass[1] : []); |
27
|
|
|
} else { |
28
|
|
|
$job = new $jobClass(); |
29
|
|
|
} |
30
|
|
|
if (!($job instanceof CronJob)) { |
31
|
|
|
throw new \Exception(sprintf( |
32
|
|
|
'%s must extend the abstract class %s', |
33
|
|
|
get_class($job), |
34
|
|
|
CronJob::class |
35
|
|
|
) |
36
|
|
|
); |
37
|
|
|
} |
38
|
|
|
if (empty($job->interval())) { |
39
|
|
|
throw new \Exception(sprintf('The interval of %s cannot be empty', get_class($job))); |
40
|
|
|
} |
41
|
|
|
$timerId = swoole_timer_tick($job->interval(), function () use ($job) { |
42
|
|
|
$this->callWithCatchException(function () use ($job) { |
43
|
|
|
$job->run(); |
44
|
|
|
}); |
45
|
|
|
}); |
46
|
|
|
$timerIds[] = $timerId; |
47
|
|
|
$job->setTimerId($timerId); |
48
|
|
|
if ($job->isImmediate()) { |
49
|
|
|
swoole_timer_after(1, function () use ($job) { |
50
|
|
|
$this->callWithCatchException(function () use ($job) { |
51
|
|
|
$job->run(); |
52
|
|
|
}); |
53
|
|
|
}); |
54
|
|
|
} |
55
|
|
|
} |
56
|
|
|
|
57
|
|
|
\swoole_process::signal(SIGUSR1, function ($signo) use ($timerIds, $process) { |
|
|
|
|
58
|
|
|
foreach ($timerIds as $timerId) { |
59
|
|
|
swoole_timer_clear($timerId); |
60
|
|
|
} |
61
|
|
|
$process->exit(0); |
62
|
|
|
}); |
63
|
|
|
}; |
64
|
|
|
|
65
|
|
|
$timerProcess = new \swoole_process($startTimer, false, false); |
66
|
|
|
if ($swoole->addProcess($timerProcess)) { |
|
|
|
|
67
|
|
|
return $timerProcess; |
68
|
|
|
} |
69
|
|
|
} |
70
|
|
|
|
71
|
|
|
} |
This check looks for parameters that have been defined for a function or method, but which are not used in the method body.