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);
Cool thanks! Also, another thing I've noticed playing with your code, your are missing only a single use statement in DebouncedJob:
use Illuminate\Queue\Jobs\Job;
(oruse \Illuminate\Contracts\Queue\Job;
?) as the Job argument of the constructor is not defined. Everything else seems awesome.Thanks for this gist. Very useful