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

Skip to content

Commit d06e0ff

Browse files
committed
Added random delay to allows delaying cron trigger startups by random amount of seconds
1 parent b01130d commit d06e0ff

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,20 +25,26 @@ final class CronExpressionTrigger implements TriggerInterface
2525
{
2626
public function __construct(
2727
private readonly CronExpression $expression = new CronExpression('* * * * *'),
28+
private readonly int $randomDelay = 0
2829
) {
2930
}
3031

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

37-
return new self(new CronExpression($expression));
38+
return new self(new CronExpression($expression), $randomDelay);
3839
}
3940

4041
public function getNextRunDate(\DateTimeImmutable $run): ?\DateTimeImmutable
4142
{
42-
return \DateTimeImmutable::createFromMutable($this->expression->getNextRunDate($run));
43+
$nextRun = $this->expression->getNextRunDate($run);
44+
if ($this->randomDelay > 0) {
45+
$nextRun->add(new \DateInterval('PT'.random_int(0, $this->randomDelay).'S'));
46+
}
47+
48+
return \DateTimeImmutable::createFromMutable($nextRun);
4349
}
4450
}

0 commit comments

Comments
 (0)