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);
Oops, thanks for pointing that out! My App\Support\Job class was just a convenience class that had the following traits:
The delay method comes from the
Queueable
trait. I went ahead and added those traits to the DebouncedJob class here - it should work now.