laravelqueuelaravel-jobs

How to delay Laravel Job Queue


I am trying to learn about Jobs and queues in Laravel , when i try to learn something new i always take a basic example by myself and try to understand the workflow better.

Okay here is the problem

I have created a Job in Laravel as you can see in the handle method i am just trying to print a simple message on the laravel.logger , this works totally fine.

class SendEmailJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;


    protected $email;
    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct($email)
    {
        $this->email = $email;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
       Log::info($this->email . '<<<<<<<<<<<<<<<');

    }
}

My problem is that i want to delay this job for 2 minutes then to dispatch it , i have tried it this way but without success both logs are printed immediately when index method is being called but i want $job = new SendEmailJob("This will show after 2 minutes"); to be called after 2 minutes an not printed immediately

public  function  index(){
        
        $on = Carbon::now()->addMinutes(2);

        Log::info('Test');

        $job = new SendEmailJob("This will show after 2 minutes");

        $job->delay($on);

        dispatch($job);

        
        return "none";
    }

Solution

  • You can take a look at the documentation: https://laravel.com/docs/8.x/queues#delayed-dispatching

    You can do following:
    (new SendEmailJob("This will show after 2 minutes"))->delay(now()->addMinutes(2)); or
    SendEmailJob::dispatch("This will show after 2 minutes")->delay(now()->addMinutes(2));