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

87 lines
2.0 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;
2021-04-16 01:42:01 +08:00
use Swoole\Coroutine;
2021-04-16 01:17:37 +08:00
use Throwable;
2021-03-26 01:01:21 +08:00
/**
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
/**
* @param \Swoole\Process $process
* @throws Exception
*/
public function onHandler(\Swoole\Process $process): void
{
2021-04-16 15:43:50 +08:00
/** @var 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 01:12:15 +08:00
$server = Snowflake::app()->getSwoole();
2021-04-16 01:18:19 +08:00
$setting = $server->setting['worker_num'] + $server->setting['task_worker_num'];
2021-04-16 00:35:55 +08:00
while (true) {
2021-04-16 00:33:13 +08:00
[$range, $redis] = $this->loadCarobTask();
foreach ($range as $value) {
$this->dispatch($server, $redis, $setting, $value);
}
$redis->release();
2021-04-16 01:42:01 +08:00
2021-04-16 01:47:49 +08:00
Coroutine::sleep(0.1);
2021-04-16 00:35:55 +08:00
}
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:09:27 +08:00
if (empty($handler = $redis->get('crontab:' . $value))) {
2021-04-16 01:07:19 +08:00
return;
}
$params['handler'] = swoole_unserialize($handler);
2021-04-16 00:33:13 +08:00
2021-04-17 15:58:24 +08:00
$server->sendMessage($params, random_int(0, $setting - 1));
2021-04-16 01:17:37 +08:00
} catch (Throwable $exception) {
2021-04-16 00:33:13 +08:00
logger()->addError($exception);
}
}
/**
* @return array
* @throws Exception
*/
private function loadCarobTask(): array
{
$redis = Snowflake::app()->getRedis();
2021-04-16 01:41:01 +08:00
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
}