DEV Community

Cover image for Laravel Dispatch Queue Job with Delay and Get Job ID
Mitul Lakhani
Mitul Lakhani

Posted on

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);
    }
}
Enter fullscreen mode Exit fullscreen mode

Now let's use "custom_dispatch" helper.

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

php artisan make:controller JobHandlerController
Enter fullscreen mode Exit fullscreen mode

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

<?php
namespace  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;
    }
}
Enter fullscreen mode Exit fullscreen mode

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

That's it!

Hope you find it useful.

Top comments (1)

Collapse
 
askoflor profile image
askoflor

hi I am a beginner on laravel and for two days I have a problem that I can not solve the problem is the following when I create a laravel project and I run the laravel server I have this problem

Avertissement : require(C:\wamp64\www\backendFunbin\bootstrap/../vendor/autoload.php) : échec de l'ouverture du flux : aucun fichier ou répertoire de ce type dans C:\wamp64\www\backendFunbin\bootstrap\ autoload.php à la ligne 17

Erreur fatale : require() : l'échec de l'ouverture requis 'C:\wamp64\www\backendFunbin\bootstrap/../vendor/autoload.php' (include_path='.;C:\php\pear') en C :\wamp64\www\backendFunbin\bootstrap\autoload.php à la ligne 17