Job Queue
This commit is contained in:
69
app/src/Service/Queue.php
Normal file
69
app/src/Service/Queue.php
Normal file
@ -0,0 +1,69 @@
|
||||
<?php
|
||||
namespace Incoviba\Service;
|
||||
|
||||
use Exception;
|
||||
use Psr\Log\LoggerInterface;
|
||||
use Incoviba\Common\Ideal;
|
||||
use Incoviba\Exception\ServiceAction\{Create, Read};
|
||||
use Incoviba\Service;
|
||||
|
||||
class Queue extends Ideal\Service
|
||||
{
|
||||
public function __construct(LoggerInterface $logger, protected Service\Job $jobService, Worker $defaultWorker)
|
||||
{
|
||||
parent::__construct($logger);
|
||||
$this->register('default', $defaultWorker);
|
||||
}
|
||||
|
||||
protected array $workers;
|
||||
public function register(string $name, Worker $worker): self
|
||||
{
|
||||
$this->workers[strtolower($name)] = $worker;
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function enqueue(array $configuration): bool
|
||||
{
|
||||
try {
|
||||
$this->jobService->add($configuration);
|
||||
return true;
|
||||
} catch (Create $exception) {
|
||||
$final = new Exception("Could not enqueue job", 0, $exception);
|
||||
$this->logger->warning($final);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public function run(): bool
|
||||
{
|
||||
try {
|
||||
$jobs = $this->jobService->getPending();
|
||||
} catch (Read $exception) {
|
||||
$final = new Exception("Could not get pending jobs", 0, $exception);
|
||||
$this->logger->warning($final);
|
||||
return false;
|
||||
}
|
||||
|
||||
$status = true;
|
||||
foreach ($jobs as $job) {
|
||||
$type = 'default';
|
||||
if (isset($job->configuration['type'])) {
|
||||
$type = strtolower($job->configuration['type']);
|
||||
}
|
||||
if (!isset($this->workers[$type])) {
|
||||
$type = 'default';
|
||||
}
|
||||
|
||||
$worker = $this->workers[$type];
|
||||
|
||||
try {
|
||||
$status &= $worker->run($job);
|
||||
} catch (Exception $exception) {
|
||||
$final = new Exception("Could not run job", 0, $exception);
|
||||
$this->logger->warning($final);
|
||||
$status &= false;
|
||||
}
|
||||
}
|
||||
return $status;
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user