Files
kiri-core/System/Process/CrontabProcess.php
T

109 lines
2.6 KiB
PHP
Raw Normal View History

2021-03-19 17:47:41 +08:00
<?php
namespace Snowflake\Process;
use ReflectionException;
2021-03-20 02:33:50 +08:00
use Snowflake\Core\Json;
2021-03-19 18:52:30 +08:00
use Snowflake\Crontab;
2021-03-19 17:47:41 +08:00
use Snowflake\Exception\ComponentException;
use Snowflake\Exception\ConfigException;
use Snowflake\Exception\NotFindClassException;
use Snowflake\Snowflake;
use Swoole\Coroutine;
use Swoole\Coroutine\Barrier;
use Swoole\Coroutine\Channel;
use Swoole\Exception;
use Swoole\Timer;
/**
* Class CrontabProcess
* @package Snowflake\Process
*/
class CrontabProcess extends Process
{
2021-03-20 02:33:50 +08:00
/** @var Crontab[] $names */
public array $names = [];
/**
* @param \Swoole\Process $process
*/
public function onHandler(\Swoole\Process $process): void
{
while (true) {
2021-03-20 02:48:29 +08:00
try {
$content = $process->read();
$_content = json_decode($content, true);
if (is_null($_content)) {
$this->jobDelivery($content);
} else {
$this->otherAction($_content);
}
} catch (\Throwable $exception) {
$this->application->error($exception->getMessage());
2021-03-20 02:33:50 +08:00
}
}
}
/**
* @param $content
*/
private function otherAction($content)
{
call_user_func(match ($content['action']) {
'clear' => function ($content) {
2021-03-20 02:56:21 +08:00
$this->clear($content['name']);
2021-03-20 02:33:50 +08:00
},
'clearAll' => function () {
foreach ($this->names as $name => $crontab) {
$crontab->clearTimer();
2021-03-20 02:56:21 +08:00
unset($this->names[$name], $crontab);
2021-03-20 02:33:50 +08:00
}
},
default => function () {
$this->application->error('unknown action');
}
2021-03-20 02:44:30 +08:00
}, $content);
2021-03-20 02:33:50 +08:00
}
2021-03-20 02:56:21 +08:00
/**
* @param string $name
*/
public function clear(string $name)
{
if (!isset($this->names[$name])) {
return;
}
$this->names[$name]->clearTimer();
}
2021-03-20 02:33:50 +08:00
/**
* @param $content
*/
private function jobDelivery($content)
{
2021-03-20 02:51:37 +08:00
/** @var Crontab $content */
2021-03-20 02:33:50 +08:00
$content = unserialize($content);
2021-03-20 02:46:29 +08:00
$runTicker = function (Crontab $crontab) {
2021-03-20 03:04:14 +08:00
$this->application->warning('execute crontab ' . date('Y-m-d H:i:s'));
2021-03-20 02:56:21 +08:00
$crontab->execute($this);
2021-03-20 02:46:29 +08:00
};
2021-03-20 03:00:55 +08:00
$timer = $content->getTickTime() * 10;
2021-03-20 02:33:50 +08:00
if ($content->isLoop()) {
2021-03-20 02:53:29 +08:00
$content->setTimerId(Timer::tick($timer, $runTicker, $content));
2021-03-20 02:33:50 +08:00
} else {
2021-03-20 02:53:29 +08:00
$content->setTimerId(Timer::after($timer, $runTicker, $content));
2021-03-20 02:33:50 +08:00
}
2021-03-20 02:53:29 +08:00
$this->names[$content->getName()] = $content;
2021-03-20 02:33:50 +08:00
}
2021-03-19 17:47:41 +08:00
}