Search code examples
laravelredisdelayed-job

How to dispatch an async job in Laravel 5.8 with Redis?


I need to run a very time consuming task asynchronous in Laravel 5.8. This is the .env file

...
QUEUE_CONNECTION=sync
QUEUE_DRIVER=redis
...

The queue driver must be Redis because the website uses Laravel-Echo with redis and socket.io to broadcast messages and I can't change queue driver to database.

This is the job I created

<?php

namespace App\Jobs;

use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;

class BroadcastRepeatJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        sleep(30);
    }
}

and this is the HomeController:

public function index()
{
    BroadcastRepeatJob::dispatch()->onQueue("default");
    dd(1);
    ...
}

and I also run the following artisan commands

php artisan queue:work
php artisan queue:listen

when I visit /index of HomeController I expect to see dd(1) immediately not after 30 seconds because the sleep(30) must be ran in a queue but this does not happen and I have to wait 30 seconds to see dd(1). How can I run the job in background asynchronous ?

Thanks in advance.


Solution

  • Try switching your QUEUE_CONNECTION to redis rather than sync

     /*
        |--------------------------------------------------------------------------
        | Queue Connections
        |--------------------------------------------------------------------------
        |
        | Here you may configure the connection information for each server that
        | is used by your application. A default configuration has been added
        | for each back-end shipped with Laravel. You are free to add more.
        |
        | Drivers: "sync", "database", "beanstalkd", "sqs", "redis", "null"
        |
        */
    
        'connections' => [
    
            'sync' => [
                'driver' => 'sync',
            ],
    
            'database' => [
                'driver'        => 'database',
                'table'         => 'jobs',
                'queue'         => 'default',
                'retry_after'   => 90,
            ],
    
            'redis' => [
                'driver'        => 'redis',
                'connection'    => 'default',
                'queue'         => env('REDIS_QUEUE', 'default'),
                'retry_after'   => 90,
                'block_for'     => null,
            ],
    
        ],