April 14, 2018 —John Koster
The dispatch_now
function can be used to process a job within the current PHP process. This function will skip the job queue entirely and execute the job's task immediately.
The signature of the dispatch_now
function is:
1function dispatch_now(2 $job,3 $handler = null4);
We will create a simple job that will dump the value Hello, Universe
value and stop the script's execution.
In app/Jobs/SayHello.php
:
1<?php 2 3namespace App\Jobs; 4 5use Illuminate\Bus\Queueable; 6use Illuminate\Queue\SerializesModels; 7use Illuminate\Queue\InteractsWithQueue; 8use Illuminate\Contracts\Queue\ShouldQueue; 9use Illuminate\Foundation\Bus\Dispatchable;10 11class SayHello implements ShouldQueue12{13 use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;14 15 /**16 * Create a new job instance.17 *18 * @return void19 */20 public function __construct()21 {22 //23 }24 25 /**26 * Execute the job.27 *28 * @return void29 */30 public function handle()31 {32 dd('Hello, Universe');33 }34}
We can observe the behavior of the dispatch_now
function by invoking it like so:
1$job = new App\Jobs\SayHello;2 3dispatch_now($job);
If the above code was executed in a browser, the following would be displayed on the screen:
1Hello, Universe
∎
The following amazing people help support this site and my open source projects ♥️
If you're interesting in supporting my work and want to show up on this list, check out my GitHub Sponsors Profile.