To delay the execution of a job in Laravel queues, you can use the delay
method provided by the Illuminate\Bus\Queueable
trait. Here are the steps to follow:
Illuminate\Contracts\Queue\ShouldQueue
interface:namespace App\Jobs;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
class ExampleJob implements ShouldQueue
{
use Dispatchable, Queueable;
/**
* Execute the job.
*
* @return void
*/
public function handle()
{
// Job logic goes here
}
}
delay
method inside the job's dispatch
method to delay the execution by a specified number of seconds:namespace App\Jobs;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
class ExampleJob implements ShouldQueue
{
use Dispatchable, Queueable;
public function __construct()
{
//
}
/**
* Execute the job.
*
* @return void
*/
public function handle()
{
// Job logic goes here
}
/**
* The number of seconds to wait before executing the job.
*
* @return int
*/
public function delay()
{
return 60; // Delay execution by 60 seconds
}
}
dispatch
method on the job class:use App\Jobs\ExampleJob;
ExampleJob::dispatch()->delay(now()->addMinutes(5));
In the above example, the job ExampleJob
will be executed after a delay of 5 minutes. You can adjust the delay time according to your requirements by using Laravel's date and time helper functions.