Skip to content

Commit

Permalink
Remove not need mutator method or make them private.
Browse files Browse the repository at this point in the history
Update documentation
Setup messenger configuration for sandbox
  • Loading branch information
mpoiriert committed Apr 21, 2024
1 parent de5732b commit 43af43b
Show file tree
Hide file tree
Showing 11 changed files with 119 additions and 122 deletions.
1 change: 1 addition & 0 deletions config/packages/messenger.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ framework:
sync: 'sync://'

routing:
Draw\Component\CronJob\Message\ExecuteCronJobMessage: 'async_high_priority'
App\Message\NewTestDocumentMessage: ['sync', 'async']
Draw\Component\Messenger\ManualTrigger\Message\ManuallyTriggeredInterface: 'async'
Draw\Bundle\UserBundle\Message\NewUserLockMessage: 'sync'
Expand Down
2 changes: 1 addition & 1 deletion packages/cron-job/Command/QueueDueCronJobsCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ protected function execute(InputInterface $input, OutputInterface $output): int

$io->note(sprintf('Queueing cron job "%s"...', $cronJob->getName()));

$this->cronJobProcessor->queue($cronJob);
$this->cronJobProcessor->queue($cronJob, false);
}

$io->success('Cron jobs successfully queued...');
Expand Down
2 changes: 1 addition & 1 deletion packages/cron-job/CronJobProcessor.php
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ public function __construct(
) {
}

public function queue(CronJob $cronJob, bool $force = false): void
public function queue(CronJob $cronJob, bool $force): void
{
$manager = $this->managerRegistry->getManagerForClass(CronJobExecution::class);

Expand Down
40 changes: 16 additions & 24 deletions packages/cron-job/Entity/CronJob.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;

#[
ORM\Entity,
Expand All @@ -23,21 +24,31 @@ class CronJob implements \Stringable
private ?int $id = null;

#[ORM\Column(name: 'name', type: 'string', length: 255, unique: true, nullable: false)]
#[
Assert\NotNull,
Assert\Length(min: 1, max: 255),
]
private ?string $name = null;

#[ORM\Column(name: 'active', type: 'boolean', nullable: false, options: ['default' => false])]
private bool $active = false;

#[ORM\Column(name: 'command', type: 'text', nullable: false)]
#[Assert\NotNull]
private ?string $command = null;

#[ORM\Column(name: 'schedule', type: 'string', length: 255, nullable: true)]
private ?string $schedule = null;

#[ORM\Column(name: 'time_to_live', type: 'integer', nullable: false, options: ['default' => 0])]
#[
Assert\NotNull,
Assert\GreaterThanOrEqual(0),
]
private int $timeToLive = 0;

#[ORM\Column(name: 'priority', type: 'integer', nullable: true)]
#[Assert\Range(min: 0, max: 255)]
private ?int $priority = null;

/**
Expand Down Expand Up @@ -148,26 +159,6 @@ public function getExecutions(): Collection
return $this->executions;
}

public function addExecution(CronJobExecution $execution): self
{
if (!$this->executions->contains($execution)) {
$this->executions->add($execution);
$execution->setCronJob($this);
}

return $this;
}

public function removeExecution(CronJobExecution $execution): self
{
if ($this->executions->contains($execution)) {
$this->executions->removeElement($execution);
$execution->setCronJob(null);
}

return $this;
}

public function isDue(): bool
{
if (null === $this->getSchedule()) {
Expand All @@ -179,10 +170,11 @@ public function isDue(): bool

public function newExecution(bool $force = false): CronJobExecution
{
return (new CronJobExecution())
->setCronJob($this)
->setRequestedAt(new \DateTimeImmutable())
->setForce($force);
$cronJobExecution = new CronJobExecution($this, new \DateTimeImmutable(), $force);

$this->executions->add($cronJobExecution);

return $cronJobExecution;
}

public function __toString(): string
Expand Down
56 changes: 24 additions & 32 deletions packages/cron-job/Entity/CronJobExecution.php
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ class CronJobExecution implements \Stringable
private ?int $id = null;

#[ORM\Column(name: 'requested_at', type: 'datetime_immutable', nullable: false)]
private ?\DateTimeImmutable $requestedAt = null;
private \DateTimeImmutable $requestedAt;

#[ORM\Column(name: '`force`', type: 'boolean', nullable: false, options: ['default' => false])]
private bool $force = false;
Expand Down Expand Up @@ -52,7 +52,17 @@ class CronJobExecution implements \Stringable
onDelete: 'CASCADE',
)
]
private ?CronJob $cronJob = null;
private CronJob $cronJob;

public function __construct(
CronJob $cronJob,
\DateTimeImmutable $requestedAt,
bool $force
) {
$this->cronJob = $cronJob;
$this->requestedAt = $requestedAt;
$this->force = $force;
}

public function getId(): ?int
{
Expand All @@ -64,31 +74,17 @@ public function getRequestedAt(): ?\DateTimeImmutable
return $this->requestedAt;
}

public function setRequestedAt(?\DateTimeImmutable $requestedAt): self
{
$this->requestedAt = $requestedAt;

return $this;
}

public function isForce(): bool
{
return $this->force;
}

public function setForce(bool $force): self
{
$this->force = $force;

return $this;
}

public function getExecutionStartedAt(): ?\DateTimeImmutable
{
return $this->executionStartedAt;
}

public function setExecutionStartedAt(?\DateTimeImmutable $executionStartedAt): self
private function setExecutionStartedAt(?\DateTimeImmutable $executionStartedAt): self
{
$this->executionStartedAt = $executionStartedAt;

Expand All @@ -100,7 +96,7 @@ public function getExecutionEndedAt(): ?\DateTimeImmutable
return $this->executionEndedAt;
}

public function setExecutionEndedAt(?\DateTimeImmutable $executionEndedAt): self
private function setExecutionEndedAt(?\DateTimeImmutable $executionEndedAt): self
{
$this->executionEndedAt = $executionEndedAt;

Expand All @@ -112,7 +108,7 @@ public function getExecutionDelay(): ?int
return $this->executionDelay;
}

public function setExecutionDelay(?int $executionDelay): self
private function setExecutionDelay(?int $executionDelay): self
{
$this->executionDelay = $executionDelay;

Expand All @@ -124,7 +120,7 @@ public function getExitCode(): ?int
return $this->exitCode;
}

public function setExitCode(?int $exitCode): self
private function setExitCode(?int $exitCode): self
{
$this->exitCode = $exitCode;

Expand All @@ -136,7 +132,7 @@ public function getError(): ?array
return $this->error;
}

public function setError(?array $error): self
private function setError(?array $error): self
{
$this->error = $error;

Expand All @@ -148,13 +144,6 @@ public function getCronJob(): ?CronJob
return $this->cronJob;
}

public function setCronJob(?CronJob $cronJob): self
{
$this->cronJob = $cronJob;

return $this;
}

public function isExecutable(\DateTimeImmutable $dateTime): bool
{
if (!($cronJob = $this->getCronJob())?->isActive()) {
Expand All @@ -179,19 +168,22 @@ public function start(): void
->setExecutionEndedAt(null);
}

public function end(): void
public function end(): static
{
$this
->setExitCode(0)
->setExecutionEndedAt($executionEndedAt = new \DateTimeImmutable())
->setExecutionDelay($executionEndedAt->getTimestamp() - $this->getExecutionStartedAt()->getTimestamp());
->setExecutionDelay(
$executionEndedAt->getTimestamp() - $this->getExecutionStartedAt()->getTimestamp()
);

return $this;
}

public function fail(?int $exitCode, ?array $error): void
{
$this->end();

$this
->end()
->setExitCode($exitCode)
->setError($error);
}
Expand Down
17 changes: 15 additions & 2 deletions packages/cron-job/README.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
# Cron Job

This library is used to manage and process cron jobs.
This library is used to manage and process cron jobs from the database.

The cron are sent to a queue and processed by a worker via symfony messenger.

## Configuration

Expand Down Expand Up @@ -57,9 +59,20 @@ draw_sonata_integration:
translation_domain: SonataAdminBundle
```
### Messenger
You need to configure the routing for the messenger component for the message that will be used to process the cron jobs.
```yaml
framework:
messenger:
routing:
Draw\Component\CronJob\Message\ExecuteCronJobMessage: 'async'
```
## Usage
Once the package is enabled, a new admin page will be available - **Cron Job**. The package also provides
2 console commands:
- **draw:cron-job:queue-due** - it is used to process due cron jobs by their configs; it can be configured in the **crontab**
- **draw:cron-job:queue-due** - it is used to process due cron jobs by their configs; it should be configured as a cron to be executed with * * * * *
- **draw:cron-job:queue-by-name** - it allows to manually process a cron job by its name passed as an argument
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,7 @@ public function testExecute(array $rawCronJobs, array $expectedDisplay): void
->method('queue')
->with(
...static::withConsecutive(...array_map(
static fn (CronJob $cronJob): array => [$cronJob],
static fn (CronJob $cronJob): array => [$cronJob, false],
$dueCronJobs
))
);
Expand Down
19 changes: 8 additions & 11 deletions packages/cron-job/Tests/CronJobProcessorTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -31,8 +31,6 @@ class CronJobProcessorTest extends TestCase

private CronJobProcessor $cronJobProcessor;

private ManagerRegistry&MockObject $managerRegistry;

private EventDispatcherInterface&MockObject $eventDispatcher;

private ProcessFactoryInterface&MockObject $processFactory;
Expand All @@ -43,17 +41,15 @@ class CronJobProcessorTest extends TestCase

protected function setUp(): void
{
parent::setUp();

$this->managerRegistry = $this->createMock(ManagerRegistry::class);
$this->managerRegistry
$managerRegistry = $this->createMock(ManagerRegistry::class);
$managerRegistry
->expects(static::any())
->method('getManagerForClass')
->with(CronJobExecution::class)
->willReturn($this->entityManager = $this->createMock(EntityManagerInterface::class));

$this->cronJobProcessor = new CronJobProcessor(
$this->managerRegistry,
$managerRegistry,
new ParameterBag([
'kernel.cache_dir' => '/var/cache',
]),
Expand Down Expand Up @@ -261,9 +257,10 @@ public function testProcessWithCancelledExecution(): void

private function createCronJobExecution(string $command = 'bin/console draw:test:execute'): CronJobExecution
{
return (new CronJobExecution())
->setCronJob(
(new CronJob())->setCommand($command)
);
return new CronJobExecution(
(new CronJob())->setCommand($command),
new \DateTimeImmutable(),
false
);
}
}
16 changes: 9 additions & 7 deletions packages/cron-job/Tests/Entity/CronJobExecutionTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -24,13 +24,13 @@ public function testIsExecutable(
): void {
Carbon::setTestNow($now);

$execution = (new CronJobExecution())
->setRequestedAt($requestedAt)
->setCronJob(
(new CronJob())
->setActive($active)
->setTimeToLive($timeToLive)
);
$execution = new CronJobExecution(
(new CronJob())
->setActive($active)
->setTimeToLive($timeToLive),
$requestedAt,
false
);

static::assertSame($expectedExecutable, $execution->isExecutable(Carbon::now()->toDateTimeImmutable()));
}
Expand All @@ -40,6 +40,8 @@ public static function provideDataForTestIsExecutable(): iterable
yield 'inactive' => [
'$expectedExecutable' => false,
'$active' => false,
'$timeToLive' => 0,
'$requestedAt' => new \DateTimeImmutable('2024-04-17 00:00:00'),
];

yield 'active with no time to live' => [
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ public function queueAction(
CronJob $cronJob,
CronJobProcessor $cronJobProcessor
): Response {
$cronJobProcessor->queue($cronJob);
$cronJobProcessor->queue($cronJob, true);

$this->addFlash(
'sonata_flash_success',
Expand Down
Loading

0 comments on commit 43af43b

Please sign in to comment.