Search code examples
phplaravelqueuejobsschedule

How do I schedule a queue job synchronously on Laravel


Pretty much what the title says, when I write this on kernel.php

$schedule->job(new Heartbeat)->everyFiveMinutes();

It runs the code asynchronously, is there anyway I could do a dispatchNow() on a schedule?

I am using Laravel 7


Solution

  • You may use onConnection method to set the driver on-the-fly.

    $schedule->job((new Heartbeat)->onConnection('sync'))->everyFiveMinutes();
    

    Another option may be while calling the job method, setting the connection.

    /**
     * Add a new job callback event to the schedule.
     *
     * @param  object|string  $job
     * @param  string|null  $queue
     * @param  string|null  $connection
     * @return \Illuminate\Console\Scheduling\CallbackEvent
     */
    public function job($job, $queue = null, $connection = null)
    {
        return $this->call(function () use ($job, $queue, $connection) {
            $job = is_string($job) ? Container::getInstance()->make($job) : $job;
    
            if ($job instanceof ShouldQueue) {
                $this->dispatchToQueue($job, $queue ?? $job->queue, $connection ?? $job->connection);
            } else {
                $this->dispatchNow($job);
            }
        })->name(is_string($job) ? $job : get_class($job));
    }