PHP code example of bouzentm / laravel-queue-debounce
1. Go to this page and download the library: Download bouzentm/laravel-queue-debounce library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
bouzentm / laravel-queue-debounce example snippets
use Bouzentm\LaravelQueueDebounce\Debounceable;
class SyncContactJob implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
use Debounceable;
protected function debounceKey(): string
{
return 'sync-contact:' . $this->contactId;
}
public function __construct(public int $contactId)
{
$this->debounceDelay = 30; // seconds
}
public function handle(): void
{
Contact::find($this->contactId)->syncToCrm();
}
}
// In your listener or model:
class Contact extends Model
{
protected static function booted(): void
{
static::saved(function (Contact $contact) {
// Even if called 100 times in 30 seconds, only ONE job executes
SyncContactJob::debounce($contact->id);
});
}
}
class UpdateTicketJob implements ShouldQueue
{
use Debounceable;
protected function debounceKey(): string
{
return "update-ticket:{$this->ticketId}:{$this->updateType}";
}
public function __construct(
public int $ticketId,
public string $updateType
) {
$this->debounceDelay = 60;
}
}
// These are DIFFERENT debounce windows:
UpdateTicketJob::debounce(123, 'status'); // Window 1
UpdateTicketJob::debounce(123, 'priority'); // Window 2
UpdateTicketJob::debounce(456, 'status'); // Window 3
public function middleware(): array
{
return [
...$this->debounceMiddleware(),
new WithoutOverlapping($this->contactId),
];
}
class PrepareReplyJob implements ShouldQueue
{
use Debounceable;
// Don't redeclare $debounceDelay here
public function __construct(public int $contactId)
{
$this->debounceDelay = 1200; // 20 minutes
}
}
use Illuminate\Support\Facades\Redis;
it('debounces multiple calls into one job', function () {
Redis::shouldReceive('getset')
->once()->andReturn(false) // first call: no key
->once()->andReturn(now()->addSeconds(30)->getTimestamp()); // second: pending
Redis::shouldReceive('expire')->twice();
SyncContactJob::debounce(123);
SyncContactJob::debounce(123);
Queue::assertPushed(SyncContactJob::class, 1);
});
Loading please wait ...
Before you can download the PHP files, the dependencies should be resolved. This can take some minutes. Please be patient.