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

116 lines
2.2 KiB
PHP
Raw Normal View History

2021-03-26 01:01:21 +08:00
<?php
namespace Snowflake\Crontab;
use Exception;
2021-03-29 11:36:09 +08:00
use ReflectionException;
2021-03-26 01:01:21 +08:00
use Snowflake\Event;
2021-03-29 11:36:09 +08:00
use Snowflake\Exception\ComponentException;
use Snowflake\Exception\ConfigException;
use Snowflake\Exception\NotFindClassException;
2021-03-26 01:01:21 +08:00
use Snowflake\Process\Process;
use Snowflake\Snowflake;
2021-03-26 01:39:22 +08:00
use Swoole\Coroutine;
2021-03-26 01:01:21 +08:00
/**
* Class Consumer
* @package Snowflake\Crontab
*/
class Consumer extends Process
{
2021-03-29 10:39:36 +08:00
public Coroutine\Channel $channel;
/**
* @param \Swoole\Process $process
* @throws Exception
*/
public function onHandler(\Swoole\Process $process): void
{
if (Snowflake::getPlatform()->isLinux()) {
2021-03-29 11:36:09 +08:00
name($this->pid, 'Crontab consumer');
2021-03-29 10:39:36 +08:00
}
$this->channel = new Coroutine\Channel(2000);
go(function () {
$this->popChannel();
});
$this->tick($process);
}
/**
* @throws Exception
*/
public function popChannel()
{
/** @var Crontab $crontab */
$crontab = $this->channel->pop(-1);
go(function () use ($crontab) {
try {
$crontab->increment()->execute();
if ($crontab->getExecuteNumber() < $crontab->getMaxExecuteNumber()) {
Consumer::addTask($crontab);
} else if ($crontab->isLoop()) {
Consumer::addTask($crontab);
}
} catch (\Throwable $throwable) {
2021-03-30 12:03:05 +08:00
logger()->addError($throwable,'throwable');
2021-03-29 10:39:36 +08:00
} finally {
fire(Event::SYSTEM_RESOURCE_RELEASES);
}
});
$this->popChannel();
}
/**
* @param \Swoole\Process $process
2021-03-29 11:36:09 +08:00
* @throws ReflectionException
* @throws ComponentException
* @throws ConfigException
* @throws NotFindClassException
* @throws Exception
2021-03-29 10:39:36 +08:00
*/
public function tick(\Swoole\Process $process)
{
$value = $process->read(40);
$redis = Snowflake::app()->getRedis();
$crontab = swoole_unserialize($redis->get($value));
$redis->del($value);
if (is_object($crontab)) {
$this->channel->push($crontab);
}
$redis->release();
$this->tick($process);
}
/**
* @param Crontab $crontab
* @throws Exception
*/
private static function addTask(Crontab $crontab)
{
$redis = Snowflake::app()->getRedis();
$name = md5($crontab->getName());
$redis->set('crontab:' . $name, swoole_serialize($crontab));
$tickTime = time() + $crontab->getTickTime();
$redis->zAdd(Producer::CRONTAB_KEY, $tickTime, $crontab->getName());
}
2021-03-26 01:01:21 +08:00
}