Skip to content

Commit 79aa0a4

Browse files
kbondvtsykun
andcommitted
[Scheduler] add CronExpressionTrigger::jitter()
Co-authored-by: Uladzimir Tsykun <tsykun314@gmail.com>
1 parent 6222f8e commit 79aa0a4

File tree

1 file changed

+21
-1
lines changed

1 file changed

+21
-1
lines changed

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

+21-1
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@
1414
use Cron\CronExpression;
1515
use Random\Engine\Xoshiro256StarStar;
1616
use Random\Randomizer;
17+
use Symfony\Component\Scheduler\Exception\InvalidArgumentException;
1718
use Symfony\Component\Scheduler\Exception\LogicException;
1819

1920
/**
@@ -46,6 +47,8 @@ final class CronExpressionTrigger implements TriggerInterface
4647
[0, 6],
4748
];
4849

50+
private int $jitter = 0;
51+
4952
public function __construct(
5053
private readonly CronExpression $expression = new CronExpression('* * * * *'),
5154
) {
@@ -73,9 +76,26 @@ public static function fromSpec(string $expression = '* * * * *', string $contex
7376
return new self(new CronExpression(self::parseHashed($expression, $context)));
7477
}
7578

79+
public function jitter(int $value = 60): self
80+
{
81+
if ($value < 0 || $value > 60) {
82+
throw new InvalidArgumentException('The jitter value must be between 0 and 60.');
83+
}
84+
85+
$this->jitter = $value;
86+
87+
return $this;
88+
}
89+
7690
public function getNextRunDate(\DateTimeImmutable $run): ?\DateTimeImmutable
7791
{
78-
return \DateTimeImmutable::createFromMutable($this->expression->getNextRunDate($run));
92+
$nextRun = \DateTimeImmutable::createFromMutable($this->expression->getNextRunDate($run));
93+
94+
if ($this->jitter > 0) {
95+
$nextRun = $nextRun->add(new \DateInterval(sprintf('PT%sS', random_int(0, $this->jitter))));
96+
}
97+
98+
return $nextRun;
7999
}
80100

81101
private static function parseHashed(string $expression, string $context): string

0 commit comments

Comments
 (0)