[cron-job] allow a cronjob to pass data from one execution to another

When a cronjob is executed, it may return an array of data.

This data will be passed as parameter on the next execution
This commit is contained in:
2023-07-12 11:36:26 +02:00
parent e38b369149
commit 3f66e1a862
7 changed files with 137 additions and 11 deletions

View File

@@ -14,6 +14,7 @@ namespace Chill\MainBundle\Cron;
use Chill\MainBundle\Entity\CronJobExecution;
use Chill\MainBundle\Repository\CronJobExecutionRepositoryInterface;
use DateTimeImmutable;
use Doctrine\DBAL\Types\Types;
use Doctrine\ORM\EntityManagerInterface;
use Exception;
use Psr\Log\LoggerInterface;
@@ -46,6 +47,8 @@ class CronManager implements CronManagerInterface
private const UPDATE_BEFORE_EXEC = 'UPDATE ' . CronJobExecution::class . ' cr SET cr.lastStart = :now WHERE cr.key = :key';
private const UPDATE_LAST_EXECUTION_DATA = 'UPDATE ' . CronJobExecution::class . ' cr SET cr.lastExecutionData = :data WHERE cr.key = :key';
private CronJobExecutionRepositoryInterface $cronJobExecutionRepository;
private EntityManagerInterface $entityManager;
@@ -85,6 +88,9 @@ class CronManager implements CronManagerInterface
foreach ($orderedJobs as $job) {
if ($job->canRun($lasts[$job->getKey()] ?? null)) {
if (array_key_exists($job->getKey(), $lasts)) {
$executionData = $lasts[$job->getKey()]->getLastExecutionData();
$this->entityManager
->createQuery(self::UPDATE_BEFORE_EXEC)
->setParameters([
@@ -96,12 +102,17 @@ class CronManager implements CronManagerInterface
$execution = new CronJobExecution($job->getKey());
$this->entityManager->persist($execution);
$this->entityManager->flush();
$executionData = $execution->getLastExecutionData();
}
$this->entityManager->clear();
// note: at this step, the entity manager does not have any entity CronJobExecution
// into his internal memory
try {
$this->logger->info(sprintf('%sWill run job', self::LOG_PREFIX), ['job' => $job->getKey()]);
$job->run();
$result = $job->run($executionData);
$this->entityManager
->createQuery(self::UPDATE_AFTER_EXEC)
@@ -112,6 +123,14 @@ class CronManager implements CronManagerInterface
])
->execute();
if (null !== $result) {
$this->entityManager
->createQuery(self::UPDATE_LAST_EXECUTION_DATA)
->setParameter('data', $result, Types::JSON)
->setParameter('key', $job->getKey(), Types::STRING)
->execute();
}
$this->logger->info(sprintf('%sSuccessfully run job', self::LOG_PREFIX), ['job' => $job->getKey()]);
return;
@@ -133,7 +152,7 @@ class CronManager implements CronManagerInterface
}
/**
* @return array<0: CronJobInterface[], 1: array<string, CronJobExecution>>
* @return array{0: array<CronJobInterface>, 1: array<string, CronJobExecution>}
*/
private function getOrderedJobs(): array
{
@@ -174,7 +193,7 @@ class CronManager implements CronManagerInterface
{
foreach ($this->jobs as $job) {
if ($job->getKey() === $forceJob) {
$job->run();
$job->run([]);
}
}
}