Files
kiri-core/kiri-task/OnServerTask.php
T

95 lines
1.6 KiB
PHP
Raw Normal View History

2022-01-17 18:45:00 +08:00
<?php
namespace Kiri\Task;
use Kiri\Annotation\Inject;
use Kiri\Abstracts\Logger;
use Kiri\Exception\ConfigException;
use Kiri\Task\OnTaskInterface;
use Swoole\Server;
/**
* Class OnServerTask
* @package Server\Task
*/
class OnServerTask
{
#[Inject(Logger::class)]
public Logger $logger;
/**
* @param Server $server
* @param int $task_id
* @param int $src_worker_id
* @param mixed $data
* @throws ConfigException
*/
2022-06-16 17:38:23 +08:00
public function onTask(Server $server, int $task_id, int $src_worker_id, mixed $data): void
2022-01-17 18:45:00 +08:00
{
try {
$data = $this->resolve($data);
} catch (\Throwable $exception) {
$data = jTraceEx($exception);
2022-06-22 16:29:42 +08:00
$this->logger->error('task', [throwable($exception)]);
2022-01-17 18:45:00 +08:00
} finally {
$server->finish($data);
}
}
/**
* @param Server|null $server
* @param Server\Task $task
* @throws ConfigException
*/
2022-06-16 17:38:23 +08:00
public function onCoroutineTask(?Server $server, Server\Task $task): void
2022-01-17 18:45:00 +08:00
{
try {
$data = $this->resolve($task->data);
} catch (\Throwable $exception) {
$data = jTraceEx($exception);
2022-06-22 16:29:42 +08:00
$this->logger->error('task', [throwable($exception)]);
2022-01-17 18:45:00 +08:00
} finally {
$task->finish($data);
}
}
/**
* @param $data
* @return null
*/
private function resolve($data)
{
$execute = unserialize($data);
if ($execute instanceof OnTaskInterface) {
return $execute->execute();
}
return null;
}
/**
* @param Server $server
* @param int $task_id
* @param mixed $data
*/
2022-06-16 17:38:23 +08:00
public function onFinish(Server $server, int $task_id, mixed $data): void
2022-01-17 18:45:00 +08:00
{
if (!($data instanceof OnTaskInterface)) {
return;
}
$data->finish($server, $task_id);
}
}