chill-bundles/src/Bundle/ChillMainBundle/Service/AddressGeographicalUnit/RefreshAddressToGeographicalUnitMaterializedViewCronJob.php

57 lines
1.5 KiB
PHP

<?php
declare(strict_types=1);
/*
* Chill is a software for social workers
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace Chill\MainBundle\Service\AddressGeographicalUnit;
use Chill\MainBundle\Cron\CronJobInterface;
use Chill\MainBundle\Entity\CronJobExecution;
use DateInterval;
use DateTimeImmutable;
use Doctrine\DBAL\Connection;
use UnexpectedValueException;
class RefreshAddressToGeographicalUnitMaterializedViewCronJob implements CronJobInterface
{
private Connection $connection;
public function __construct(Connection $connection)
{
$this->connection = $connection;
}
public function canRun(?CronJobExecution $cronJobExecution): bool
{
if (null === $cronJobExecution) {
return true;
}
if ($cronJobExecution->getKey() !== $this->getKey()) {
throw new UnexpectedValueException();
}
$now = new DateTimeImmutable('now');
return $cronJobExecution->getLastStart() < $now->sub(new DateInterval('P1D'))
// introduce a random component to ensure a roll when multiple instances are hosted on same machines
&& random_int(0, 10) === 0;
}
public function getKey(): string
{
return 'refresh-materialized-view-address-to-geog-units';
}
public function run(): void
{
$this->connection->executeQuery('REFRESH MATERIALIZED VIEW view_chill_main_address_geographical_unit');
}
}