Manejo de trabajos en cli por php en vez de cron
This commit is contained in:
63
cli/src/Command/BaseLoop.php
Normal file
63
cli/src/Command/BaseLoop.php
Normal file
@ -0,0 +1,63 @@
|
||||
<?php
|
||||
namespace Incoviba\Command;
|
||||
|
||||
use Throwable;
|
||||
use DateTimeInterface;
|
||||
use DateTimeImmutable;
|
||||
use Psr\Log\LoggerInterface;
|
||||
use Symfony\Component\Console;
|
||||
use Incoviba\Service\Schedule;
|
||||
|
||||
#[Console\Attribute\AsCommand(
|
||||
name: 'loop',
|
||||
description: 'Run base loop',
|
||||
)]
|
||||
class BaseLoop extends Console\Command\Command
|
||||
{
|
||||
public function __construct(protected LoggerInterface $logger, protected Schedule $scheduleService, ?string $name = null)
|
||||
{
|
||||
parent::__construct($name);
|
||||
}
|
||||
|
||||
public function execute(Console\Input\InputInterface $input, Console\Output\OutputInterface $output): int
|
||||
{
|
||||
$output->writeln("Running Loop...");
|
||||
|
||||
// wait for next minute
|
||||
$now = new DateTimeImmutable();
|
||||
$nextMinute = new DateTimeImmutable($now->format('Y-m-d H:i:00'));
|
||||
$nextMinute->add(new \DateInterval('PT1M'));
|
||||
$diff = $nextMinute->getTimestamp() - $now->getTimestamp();
|
||||
if ($diff > 0) {
|
||||
$output->writeln("Waiting {$diff} seconds...");
|
||||
sleep($diff);
|
||||
}
|
||||
|
||||
$output->writeln('Starting loop...');
|
||||
while (true) {
|
||||
$commands = $this->scheduleService->run();
|
||||
foreach ($commands as $command) {
|
||||
$this->runCommand($input, $output, $command);
|
||||
}
|
||||
}
|
||||
return self::SUCCESS;
|
||||
}
|
||||
protected function runCommand(Console\Input\InputInterface $input, Console\Output\OutputInterface $output, string $commandName): int
|
||||
{
|
||||
try {
|
||||
$command = $this->getApplication()->find($commandName);
|
||||
} catch (Console\Exception\CommandNotFoundException $exception) {
|
||||
$this->logger->warning($exception);
|
||||
}
|
||||
|
||||
$cmd = new Console\Input\ArrayInput([
|
||||
'command' => $commandName
|
||||
]);
|
||||
try {
|
||||
return $this->getApplication()->doRun($cmd, $output);
|
||||
} catch (Throwable $exception) {
|
||||
$this->logger->warning($exception);
|
||||
return self::FAILURE;
|
||||
}
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user