Skip to content

Commit

Permalink
feat: clean up excutions
Browse files Browse the repository at this point in the history
  • Loading branch information
rugbymauri committed Aug 24, 2023
1 parent e07f3db commit 9986e46
Show file tree
Hide file tree
Showing 3 changed files with 47 additions and 0 deletions.
34 changes: 34 additions & 0 deletions src/Command/ExecuteCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -141,6 +141,40 @@ protected function execute(InputInterface $input, OutputInterface $output): int
$this->entityManager->flush($execution);
$this->eventDispatcher->dispatch(new CronFinishEvent($cronJob), CronFinishEvent::NAME);


// cleanup Executions
foreach ($cronJob->getExecutionRetention() as $state => $maxRetained) {
$expr = $this->entityManager->getExpressionBuilder();

$topIds = $this->entityManager->getRepository(Execution::class)->createQueryBuilder('execution')
->select('execution.id')
->where('execution.job = :jobClass')
->andWhere('execution.state = :state')
->orderBy('execution.startedAt', 'DESC')
->setMaxResults($maxRetained)
->setParameter('jobClass', $cronJob::class)
->setParameter('state', $state)
->getQuery()
->getScalarResult();

if (empty($topIds)) {
continue;
}

$topIds = array_map(fn($item) => $item['id'], $topIds);

$this->entityManager->getRepository(Execution::class)->createQueryBuilder('execution')
->delete()
->where('execution.job = :jobClass')
->andWhere('execution.state = :state')
->andWhere('execution.id NOT IN (:topIds)')
->setParameter('jobClass', $cronJob::class)
->setParameter('state', $state)
->setParameter('topIds', $topIds)
->getQuery()
->execute();
}

return Command::SUCCESS;
}

Expand Down
11 changes: 11 additions & 0 deletions src/CronJob/AbstractCronJob.php
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@

namespace whatwedo\CronBundle\CronJob;

use whatwedo\CronBundle\Entity\Execution;
use whatwedo\CronBundle\Manager\CronJobManager;

abstract class AbstractCronJob implements CronJobInterface
Expand Down Expand Up @@ -78,4 +79,14 @@ public function isActive(): bool
{
return true;
}

public function getExecutionRetention(): array
{
return [
Execution::STATE_ERROR => 10,
Execution::STATE_FINISHED => 10,
Execution::STATE_STALE => 10,
Execution::STATE_TERMINATED => 10,
];
}
}
2 changes: 2 additions & 0 deletions src/CronJob/CronInterface.php
Original file line number Diff line number Diff line change
Expand Up @@ -53,4 +53,6 @@ public function isParallelAllowed(): bool;
* Returns if the Job is enabled or not.
*/
public function isActive(): bool;

public function getExecutionRetention(): array;
}

0 comments on commit 9986e46

Please sign in to comment.