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);
Good catch. That should be a reference to the
App\Support\Jobs\Job
convenience class that I had, but since I removed that convenience class here, that argument should no longer be typed. I've updated the gist accordingly.