Files
oficial/cli/src/Command/BaseLoop.php

78 lines
2.5 KiB
PHP
Raw Normal View History

<?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
{
2025-05-13 15:40:32 -04:00
$this->write($output, 'Running loop...');
2025-05-13 15:40:32 -04:00
$this->waitNextMinute($output);
2025-05-13 15:40:32 -04:00
$this->write($output, 'Starting loop...');
while (true) {
2025-05-13 15:15:20 -04:00
$commands = $this->scheduleService->getPending();
foreach ($commands as $command) {
$this->runCommand($input, $output, $command);
2025-05-13 15:15:20 -04:00
sleep(10);
}
}
return self::SUCCESS;
}
2025-05-13 15:40:32 -04:00
protected function waitNextMinute(Console\Output\OutputInterface $output): void
{
// wait for next minute
$now = new DateTimeImmutable();
$nextMinute = new DateTimeImmutable($now->format('Y-m-d H:i:00'));
2025-05-13 15:47:18 -04:00
$nextMinute = $nextMinute->add(new \DateInterval('PT1M'));
$this->logger->debug('Wait', [
'now' => $now->format('Y-m-d H:i:s.u'),
'nextMinute' => $nextMinute->format('Y-m-d H:i:s.u'),
]);
2025-05-13 15:40:32 -04:00
$diff = $nextMinute->getTimestamp() - $now->getTimestamp();
if ($diff > 0) {
$output->writeln("Waiting {$diff} seconds...");
sleep($diff);
}
}
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;
}
}
2025-05-13 15:40:32 -04:00
protected function write(Console\Output\OutputInterface $output, string $message): void
{
$now = new DateTimeImmutable();
$output->writeln("[{$now->format('Y-m-d H:i:s e')}] {$message}");
}
}