Skip to main content

Command Palette

Search for a command to run...

Laravel Queues with Docker

Published
2 min read

In .env change connection so queues can run asynchronously

QUEUE_CONNECTION=database

Check queue.php config file

'connections' => [
        'sync' => [
            'driver' => 'sync',
        ],
        'database' => [
            'driver' => 'database',
            'table' => 'jobs',
            'queue' => 'default',
            'retry_after' => 90,
        ],
        ...

Make sure you have jobs tabels migrated to DB

php artisan queue:table
php artisan migrate

Create your job

php artisan make:job JobExample

Handle job execution

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

    /**
     * tries to run the job maximum 5 times
     * @var int
     */
    private $tries = 5;

    /**
     * waits 1 hour before running again de job
     * @var int
     */
    private $period = 1;

    /**
     * Constructor.
     */
    public function __construct()
    {
        $this->queue = 'my-queue';
    }

    /**
     * Execute the job.
     */
    public function handle()
    {
            if($this->attempts() === 3) {
                Log::info('job finished after 3 attempts with maximum 5 available');
            } elseif ($this->attempts() < $this->tries) {
                Log::info('job released again' after 1 hour);
                $this->release(now()->addHours($this->period));
            }
    }

    /**
     * catch job failed exception.
     */
    public function failed(\Exception $exception)
    {
        Log::info('Job Failed: ' . $exception->getMessage());
    }
}

Define queue program in supervisord.conf

[program:scoaladebani-worker-unsubscribe]
process_name=%(program_name)s_%(process_num)02d
command=php /var/www/artisan queue:work --tries=12 --queue=email-unsubscribe
autostart=true
autorestart=true
numprocs=1
redirect_stderr=true
stdout_events_enabled=1

Get worker to read the new lines from config and start corresponding worker queue

docker ps
docker exec -it 5aa9229bb140 /bin/bash
supervisorctl reread
supervisorctl update
supervisorctl reload
supervisorctl status

When worker is restarted it should copy the new program defined in Dockerfile.worker

container restart 5aa9229bb140
container start 5aa9229bb140
container stop 5aa9229bb140

Eventually you can delete and build again the worker container

docker-compose down
docker-compose up -d --build