Runs a specific Job
at most once every $delay
seconds, and at least once every $maxWait
seconds. Uses Laravel's Cache
implementation to ensure that this stays true across any number of instances of the application. Works with any existing Job
by serializing it and storing it in the Cache
.
Example:
NOTE: sleep
is only for demonstration purposes and should only be found in test code, like the following.
$delay = 15;
$maxWait = 60;
$job = new Jobs\SomeJobToDebounce();
// No matter how many times DebouncedJob is triggered for $job,
// $job will only be handled once (after a 15 second delay).
$this->dispatch(new DebouncedJob($job, $delay, $maxWait));
$this->dispatch(new DebouncedJob($job, $delay, $maxWait));
$this->dispatch(new DebouncedJob($job, $delay, $maxWait));
// etc...
// Wait for the DebouncedJob to trigger so we don't override it below.
sleep($delay+1);
// $job will be handled twice: both after $delay seconds,
// once for the default key prefix and once for 'some_other_pfx'
$this->dispatch(new DebouncedJob($job, $delay, $maxWait));
$this->dispatch(new DebouncedJob($job, $delay, $maxWait));
$this->dispatch(new DebouncedJob($job, $delay, $maxWait, 'some_other_pfx'));
$this->dispatch(new DebouncedJob($job, $delay, $maxWait, 'some_other_pfx'));
// etc...
// Wait for the DebouncedJob to trigger so we don't override it below.
sleep($delay+1);
$countTimes = 100;
// $job will be handled twice.
// Once at 60 seconds ($maxWait),
// and once again at 60 + 55 seconds ($countTimes + $delay)
for ($i = 0; $i < $countTimes; $i++) {
$this->dispatch(new DebouncedJob($job, $delay, $maxWait));
sleep(1);
}
sleep($delay+1);
Love this git! But for other readers, this is also helpful https://laravel.com/docs/7.x/cache#managing-locks-across-processes
You can just lock your job down and only when it's done you can release the lock so it can be fired again.