Skip to content

[Scheduler] randomize a cron schedule #49806

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions src/Symfony/Component/Scheduler/RecurringMessage.php
Original file line number Diff line number Diff line change
Expand Up @@ -41,9 +41,9 @@ public static function every(string $frequency, object $message, string|\DateTim
return new self(new DateIntervalTrigger($interval, $from, $until), $message);
}

public static function cron(string $expression, object $message): self
public static function cron(string $expression, object $message, int $randomDelay = 0): self
{
return new self(CronExpressionTrigger::fromSpec($expression), $message);
return new self(CronExpressionTrigger::fromSpec($expression, $randomDelay), $message);
}

public static function trigger(TriggerInterface $trigger, object $message): self
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ final class CronExpressionTrigger implements TriggerInterface, \Stringable
{
public function __construct(
private readonly CronExpression $expression = new CronExpression('* * * * *'),
private readonly int $randomDelay = 0
) {
}

Expand All @@ -33,17 +34,22 @@ public function __toString(): string
return "cron: {$this->expression->getExpression()}";
}

public static function fromSpec(string $expression = '* * * * *'): self
public static function fromSpec(string $expression = '* * * * *', int $randomDelay = 0): self
{
if (!class_exists(CronExpression::class)) {
throw new LogicException(sprintf('You cannot use "%s" as the "cron expression" package is not installed; try running "composer require dragonmantank/cron-expression".', __CLASS__));
}

return new self(new CronExpression($expression));
return new self(new CronExpression($expression), $randomDelay);
}

public function getNextRunDate(\DateTimeImmutable $run): ?\DateTimeImmutable
{
return \DateTimeImmutable::createFromMutable($this->expression->getNextRunDate($run));
$nextRun = $this->expression->getNextRunDate($run);
if ($this->randomDelay > 0) {
$nextRun->add(new \DateInterval('PT'.random_int(0, $this->randomDelay).'S'));
}

return \DateTimeImmutable::createFromMutable($nextRun);
}
}