2021-03-26 01:01:21 +08:00
|
|
|
<?php
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
namespace Snowflake\Crontab;
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
use Exception;
|
|
|
|
|
use Snowflake\Process\Process;
|
|
|
|
|
use Snowflake\Snowflake;
|
|
|
|
|
use Swoole\Coroutine\WaitGroup;
|
|
|
|
|
use Swoole\Coroutine\Channel;
|
|
|
|
|
use Swoole\Timer;
|
|
|
|
|
|
|
|
|
|
/**
|
2021-03-26 02:12:34 +08:00
|
|
|
* Class ZookeeperProcess
|
2021-03-26 01:01:21 +08:00
|
|
|
* @package Snowflake\Process
|
|
|
|
|
*/
|
2021-03-26 02:12:34 +08:00
|
|
|
class ZookeeperProcess extends Process
|
2021-03-26 01:01:21 +08:00
|
|
|
{
|
|
|
|
|
|
|
|
|
|
|
2021-03-29 10:40:47 +08:00
|
|
|
private Channel $channel;
|
|
|
|
|
private WaitGroup $waitGroup;
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
/** @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
|
|
|
|
|
{
|
|
|
|
|
$crontab = Snowflake::app()->get('crontab');
|
|
|
|
|
$crontab->clearAll();
|
|
|
|
|
|
|
|
|
|
if (Snowflake::getPlatform()->isLinux()) {
|
2021-03-29 11:36:09 +08:00
|
|
|
name($this->pid, 'Crontab zookeeper.');
|
2021-03-29 10:40:47 +08:00
|
|
|
}
|
|
|
|
|
Timer::tick(1000, function () {
|
|
|
|
|
$startTime = time();
|
|
|
|
|
|
|
|
|
|
$redis = Snowflake::app()->getRedis();
|
|
|
|
|
|
|
|
|
|
$range = $redis->zRangeByScore(Producer::CRONTAB_KEY, '0', (string)$startTime);
|
|
|
|
|
$redis->zRemRangeByScore(Producer::CRONTAB_KEY, '0', (string)$startTime);
|
2021-03-29 15:05:35 +08:00
|
|
|
$redis->release();
|
2021-03-29 10:40:47 +08:00
|
|
|
|
|
|
|
|
/** @var Consumer $consumer */
|
|
|
|
|
$consumer = Snowflake::app()->get(Consumer::class);
|
|
|
|
|
|
|
|
|
|
foreach ($range as $value) {
|
|
|
|
|
$consumer->write('crontab:' . md5($value));
|
|
|
|
|
}
|
|
|
|
|
});
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* @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
|
|
|
|
|
|
|
|
|
|
|
|
|
}
|