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

90 lines
1.6 KiB
PHP
Raw Normal View History

2021-03-19 17:47:41 +08:00
<?php
namespace Snowflake\Process;
use ReflectionException;
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
{
public Channel $channel;
/**
* @param \Swoole\Process $process
*/
public function onHandler(\Swoole\Process $process): void
{
$this->channel = new Channel(5000);
Coroutine::create([$this, 'execute']);
Timer::tick(1000, [$this, 'systemLoop']);
}
/**
* @throws \Exception
*/
public function execute()
{
while (true) {
2021-03-19 18:52:30 +08:00
/** @var Crontab $list */
2021-03-19 17:47:41 +08:00
$list = $this->channel->pop(-1);
2021-03-19 18:52:30 +08:00
$list->execute();
2021-03-19 17:47:41 +08:00
}
}
/**
* @throws ReflectionException
* @throws ComponentException
* @throws ConfigException
* @throws NotFindClassException
* @throws Exception
* @throws \Exception
*/
public function systemLoop()
{
$score = time();
$redis = Snowflake::app()->getRedis();
2021-03-19 18:40:46 +08:00
$lists = $redis->zRangeByScore('system:crontab', '0', (string)$score);
$redis->zRemRangeByScore('system:crontab', '0', (string)$score);
2021-03-19 17:47:41 +08:00
2021-03-19 19:27:19 +08:00
if (empty($lists)) {
$redis->release();
return;
}
2021-03-19 17:47:41 +08:00
$barrier = Barrier::make();
foreach ($lists as $list) {
$list = unserialize($list);
2021-03-19 18:52:30 +08:00
if (!($list instanceof Crontab)) {
2021-03-19 17:47:41 +08:00
continue;
}
$this->channel->push($list);
}
Barrier::wait($barrier);
$redis->release();
}
}