Files
remote_ip/app/common/Command/Watch.php
2023-06-18 23:26:44 -04:00

65 lines
2.1 KiB
PHP

<?php
namespace ProVM\Command;
use DateTimeImmutable;
use DateInterval;
use Psr\Log\LoggerInterface;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Style\StyleInterface;
use Symfony\Component\Console\Style\SymfonyStyle;
use function Safe\shell_exec;
#[AsCommand(
name: 'watch',
hidden: false
)]
class Watch extends Command
{
public function __construct(protected string $command, protected string $period, protected LoggerInterface $logger, string $name = 'watch')
{
parent::__construct($name);
}
public function execute(InputInterface $input, OutputInterface $output): int
{
$io = new SymfonyStyle($input, $output);
$io->title('Watch');
$period = new DateInterval($this->period);
$current = $this->updateTime($period);
$io->info('Starting');
$io->info("Start: {$current->format('Y-m-d H:i:s')}");
while(true) {
$io->info('Running Update');
$this->runUpdate();
$current = $this->updateTime($period);
$wait = $current->add($period);
$io->text("Waiting until {$wait->format('Y-m-d H:i:s')}");
time_sleep_until($wait->getTimestamp());
}
return Command::SUCCESS;
}
protected function updateTime(DateInterval $interval): DateTimeImmutable
{
$t0 = new DateTimeImmutable((new DateTimeImmutable())->format('Y-m-d 00:00:00'));
$tf = new DateTimeImmutable((new DateTimeImmutable())->add(new DateInterval('P1D'))->format('Y-m-d 00:00:00'));
$now = new DateTimeImmutable();
for ($t = $t0; $t < $tf; $t = $t->add($interval)) {
$t1 = $t->add($interval);
if ($t < $now and $now < $t1) {
return $t;
}
}
return $now;
}
protected function runUpdate(StyleInterface $io): void
{
$command = "{$this->command} update";
$this->logger->info("Running '{$command}'");
$result = shell_exec($command);
$io->note($result);
}
}