Files
kiri-core/System/Crontab/Zookeeper.php
T

118 lines
2.3 KiB
PHP
Raw Normal View History

2021-03-26 01:01:21 +08:00
<?php
namespace Snowflake\Crontab;
use Exception;
2021-04-15 18:18:41 +08:00
use Snowflake\Cache\Redis;
2021-03-26 01:01:21 +08:00
use Snowflake\Process\Process;
use Snowflake\Snowflake;
use Swoole\Coroutine\Channel;
2021-04-15 18:18:41 +08:00
use Swoole\Coroutine\WaitGroup;
2021-03-26 01:01:21 +08:00
use Swoole\Timer;
/**
2021-04-12 02:55:12 +08:00
* Class Zookeeper
2021-03-26 01:01:21 +08:00
* @package Snowflake\Process
*/
2021-04-12 02:55:12 +08:00
class Zookeeper extends Process
2021-03-26 01:01:21 +08:00
{
2021-04-15 18:18:41 +08:00
private Channel $channel;
private WaitGroup $waitGroup;
2021-03-29 10:40:47 +08:00
2021-04-15 18:18:41 +08:00
/** @var Crontab[] $names */
public array $names = [];
2021-03-29 10:40:47 +08:00
2021-04-15 18:18:41 +08:00
public array $scores = [];
public array $timers = [];
2021-03-29 10:40:47 +08:00
2021-04-12 03:07:38 +08:00
2021-04-15 18:18:41 +08:00
/**
* @param \Swoole\Process $process
* @throws Exception
*/
public function onHandler(\Swoole\Process $process): void
{
$crontab = Snowflake::app()->get('crontab');
$crontab->clearAll();
if (Snowflake::getPlatform()->isLinux()) {
name($this->pid, 'Crontab zookeeper.');
}
Timer::tick(1000, function () {
[$range, $redis] = $this->loadCarobTask();
$server = Snowflake::app()->getSwoole();
$setting = $server->setting['worker_num'];
foreach ($range as $value) {
$this->dispatch($server, $redis, $setting, $value);
}
$redis->release();
});
}
2021-04-12 02:55:12 +08:00
2021-04-12 11:05:57 +08:00
/**
* @param $server
* @param Redis|\Redis $redis
* @param int $setting
* @param $value
* @throws Exception
*/
2021-04-15 18:18:41 +08:00
private function dispatch($server, Redis|\Redis $redis, int $setting, $value)
{
try {
$params['action'] = 'crontab';
$params['handler'] = $redis->get('crontab:' . $value);
2021-04-15 18:44:50 +08:00
$redis->del('crontab:' . $value);
2021-04-15 20:01:16 +08:00
$result = $server->sendMessage($params, $workerId = random_int(0, $setting - 1));
logger()->addError('send crontab to ' . $workerId . ' ' . intval($result));
2021-04-15 18:18:41 +08:00
} catch (\Throwable $exception) {
logger()->addError($exception);
}
}
/**
* @return array
* @throws Exception
*/
private function loadCarobTask(): array
{
$redis = Snowflake::app()->getRedis();
$startTime = time();
$range = $redis->zRangeByScore(Producer::CRONTAB_KEY, '0', (string)$startTime);
$redis->zRemRangeByScore(Producer::CRONTAB_KEY, '0', (string)$startTime);
return [$range, $redis];
}
/**
* @param string $name
*/
public function clear(string $name)
{
if (!isset($this->names[$name])) {
return;
}
$timers = $this->timers[$name];
$search = array_search($name, $this->scores[$timers]);
if ($search !== false) {
unset($this->scores[$timers][$search]);
}
unset($this->timers[$name], $this->names[$name]);
}
2021-03-26 01:01:21 +08:00
}