Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 2bb84c2

Browse files
committed
Added random delay to allows delaying cron trigger startups by random amount of seconds
1 parent c375406 commit 2bb84c2

File tree

2 files changed

+11
-5
lines changed

2 files changed

+11
-5
lines changed

src/Symfony/Component/Scheduler/RecurringMessage.php

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -41,9 +41,9 @@ public static function every(string $frequency, object $message, string|\DateTim
4141
return new self(new DateIntervalTrigger($interval, $from, $until), $message);
4242
}
4343

44-
public static function cron(string $expression, object $message): self
44+
public static function cron(string $expression, object $message, int $randomDelay = 0): self
4545
{
46-
return new self(CronExpressionTrigger::fromSpec($expression), $message);
46+
return new self(CronExpressionTrigger::fromSpec($expression, $randomDelay), $message);
4747
}
4848

4949
public static function trigger(TriggerInterface $trigger, object $message): self

src/Symfony/Component/Scheduler/Trigger/CronExpressionTrigger.php

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@ final class CronExpressionTrigger implements TriggerInterface, \Stringable
2525
{
2626
public function __construct(
2727
private readonly CronExpression $expression = new CronExpression('* * * * *'),
28+
private readonly int $randomDelay = 0
2829
) {
2930
}
3031

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

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

42-
return new self(new CronExpression($expression));
43+
return new self(new CronExpression($expression), $randomDelay);
4344
}
4445

4546
public function getNextRunDate(\DateTimeImmutable $run): ?\DateTimeImmutable
4647
{
47-
return \DateTimeImmutable::createFromMutable($this->expression->getNextRunDate($run));
48+
$nextRun = $this->expression->getNextRunDate($run);
49+
if ($this->randomDelay > 0) {
50+
$nextRun->sub(new \DateInterval('PT'.random_int(0, $this->randomDelay).'S'));
51+
}
52+
53+
return \DateTimeImmutable::createFromMutable($nextRun);
4854
}
4955
}

0 commit comments

Comments
 (0)