Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
September 18, 2021 05:01 pm GMT

Laravel Dispatch Queue Job with Delay and Get Job ID

With Laravel when we dispatch Queue Job asynchronously, the job is added to the queue then we have no control over it anymore. So I find a way to take control of the job, to either remove or process jobs from the queue.

Let's Start!

Create a new helper for dispatch queue job and get Job ID

if (!function_exists("custom_dispatch")) {    function custom_dispatch($job): int {        return app(\Illuminate\Contracts\Bus\Dispatcher::class)->dispatch($job);    }}

Now let's use "custom_dispatch" helper.

Create a new controller to dispatch the job and handle the job.

php artisan make:controller JobHandlerController

Now let's use our helper and implement the controller.

<?phpnamespace  App\Http\Controllers;use Illuminate\Support\Facades\DB;class JobHandlerController extends  Controller{    public function dispatchJob(): int    {        // Create your job instance with delay, so we can back here within delay and take control in our hands.        $job = new App\Jobs\YourAwesomeJob($params)->delay(now()->addSeconds(60);        // Dispath your job with our custom_dispatch helper. This will return job id from jobs table        $jobId = custom_dispatch($job);        return $jobId;    }    public function processJob(int $jobId, string $action): bool    {        // Here deleting job from the jobs table        if($action === "delete") {            DB::table('jobs')->whereIn('id', $args['jobIds'])->delete();        }        // Here update available_at field with the current timestamp, So now the queue worker will process the job immediately.         DB::table('jobs')->where('id', $jobIds)->update(['available_at' => time()]);        return true;    }}

Note: This thing is useful when the queue driver is not "sync".

That's it!

Hope you find it useful.


Original Link: https://dev.to/mitulmlakhani/laravel-delay-dispatch-queue-job-and-get-job-id-36ke

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To