简体   繁体   中英

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";
    }

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));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM