Add cronjob and repository method to find and cancel stale workflows every other day

This commit is contained in:
2024-08-12 11:45:27 +02:00
committed by Julien Fastré
parent 34edb02cd0
commit 29fec50515
2 changed files with 68 additions and 0 deletions

View File

@@ -0,0 +1,55 @@
<?php
namespace Chill\MainBundle\Service\Workflow;
use Chill\MainBundle\Cron\CronJobInterface;
use Chill\MainBundle\Entity\CronJobExecution;
use Chill\MainBundle\Repository\Workflow\EntityWorkflowRepository;
use DateInterval;
use Doctrine\DBAL\Connection;
use Psr\Log\LoggerInterface;
use Symfony\Component\Clock\ClockInterface;
use Symfony\Component\Messenger\MessageBusInterface;
class CancelStaleWorkflowCronJob implements CronJobInterface
{
public const KEY = 'remove-stale-workflow';
public const KEEP_INTERVAL = 'P90D';
private const LAST_CANCELED_WORKFLOW = 'last-canceled-workflow-id';
public function __construct(private readonly EntityWorkflowRepository $workflowRepository,
private readonly ClockInterface $clock,
private readonly MessageBusInterface $messageBus,
)
{
}
public function canRun(?CronJobExecution $cronJobExecution): bool
{
return $this->clock->now() >= $cronJobExecution->getLastEnd()->add(new DateInterval('P1D'));
}
public function getKey(): string
{
return self::KEY;
}
public function run(array $lastExecutionData): ?array
{
$olderThanDate = $this->clock->now()->sub(new DateInterval(self::KEEP_INTERVAL));
$staleWorkflowIds = $this->workflowRepository->findWorkflowsWithoutFinalStepAndOlderThan($olderThanDate);
$lastCanceled = self::LAST_CANCELED_WORKFLOW;
foreach ($staleWorkflowIds as $wId) {
$this->messageBus->dispatch(new CancelStaleWorkflow($wId));
$lastCanceled = $wId;
}
return [self::LAST_CANCELED_WORKFLOW => $lastCanceled];
}
}