Files
oficial/cli/src/Service/Schedule.php
Juan Pablo Vial 6d1a1c914a Wait for execution
2025-05-13 15:15:20 -04:00

61 lines
2.0 KiB
PHP

<?php
namespace Incoviba\Service;
use Cron\CronExpression;
use DateTimeInterface;
use DateTimeImmutable;
use Psr\Log\LoggerInterface;
class Schedule
{
public function __construct(protected LoggerInterface $logger) {}
protected string $filename = '/var/spool/cron/crontabs/root';
public function getPending(): array
{
$now = new DateTimeImmutable();
$schedule = $this->getCommandList();
$commands = [];
foreach ($schedule as $line) {
$line = trim($line);
if ($line === '') {
continue;
}
$data = $this->parseCommandLine($line);
if ($this->processSchedule($now, $data)) {
$commands[] = $data['command'];
}
}
return $commands;
}
protected function getCommandList(): array
{
if (!file_exists($this->filename)) {
return [];
}
return explode("\n", file_get_contents($this->filename));
}
protected function parseCommandLine(string $line): array
{
$regex = '/^(?<minutes>(\d{1,2}|\*|\*\/\d{1,2})?) (?<hours>(\d{1,2}|\*|\*\/\d{1,2})?) (?<day_month>(\d{1,2}|\*|\*\/\d{1,2})?) (?<month>(\d{1,2}|\*|\*\/\d{1,2})?) (?<day_week>(\d{1,2}|\*|\*\/\d{1,2})?) (?<command>.*)$/';
preg_match_all($regex, $line, $matches);
return [
'minutes' => $matches['minutes'][0],
'hours' => $matches['hours'][0],
'day_month' => $matches['day_month'][0],
'month' => $matches['month'][0],
'day_week' => $matches['day_week'][0],
'command' => trim(str_replace(['/code/bin/incoviba', '>> /logs/commands 2>&1'], '', $matches['command'][0])),
];
}
protected function processSchedule(DateTimeInterface $now, array $schedule): bool
{
$cronLine = "{$schedule['minutes']} {$schedule['hours']} {$schedule['day_month']} {$schedule['month']} {$schedule['day_week']}";
$cron = new CronExpression($cronLine);
return $cron->isDue($now);
}
}