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

99 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-16 00:33:13 +08:00
/** @var Crontab[] $names */
public array $names = [];
public array $scores = [];
public array $timers = [];
/**
* @param \Swoole\Process $process
* @throws Exception
*/
public function onHandler(\Swoole\Process $process): void
{
2021-04-16 01:03:47 +08:00
/** @var \Snowflake\Crontab\Producer $crontab */
2021-04-16 00:33:13 +08:00
$crontab = Snowflake::app()->get('crontab');
$crontab->clearAll();
if (Snowflake::getPlatform()->isLinux()) {
name($this->pid, 'Crontab zookeeper.');
}
2021-04-16 00:35:55 +08:00
while (true) {
2021-04-16 00:33:13 +08:00
[$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-16 00:35:55 +08:00
sleep(1);
}
2021-04-16 00:33:13 +08:00
}
/**
* @param $server
* @param Redis|\Redis $redis
* @param int $setting
* @param $value
* @throws Exception
*/
private function dispatch($server, Redis|\Redis $redis, int $setting, $value)
{
try {
$params['action'] = 'crontab';
2021-04-16 01:08:11 +08:00
if (($handler = $redis->get('crontab:' . $value)) === false) {
2021-04-16 01:08:52 +08:00
var_dump($handler);
2021-04-16 01:07:19 +08:00
return;
}
$params['handler'] = swoole_unserialize($handler);
2021-04-16 00:33:13 +08:00
$result = $server->sendMessage($params, $workerId = random_int(0, $setting - 1));
var_dump('send crontab to ' . $workerId . ' ' . intval($result));
} catch (\Throwable $exception) {
logger()->addError($exception);
}
}
/**
* @return array
* @throws Exception
*/
private function loadCarobTask(): array
{
$redis = Snowflake::app()->getRedis();
2021-04-16 01:00:46 +08:00
$range = $redis->zRangeByScore(Producer::CRONTAB_KEY, '0', (string)time());
2021-04-16 00:33:13 +08:00
2021-04-16 00:54:54 +08:00
$redis->zRem(Producer::CRONTAB_KEY, ...$range);
2021-04-16 00:33:13 +08:00
return [$range, $redis];
}
2021-03-26 01:01:21 +08:00
}