In laravel how do I ran a job on one queue only?

Updated: Jan 28, 2025

In laravel how do I ran a job on one queue only?

To run a job on one queue only in Laravel, you can use the withChain method along with the onQueue method when dispatching the job. This method allows you to chain multiple jobs together, each with a different queue assignment.

Here's an example of how you can dispatch a job to run on a specific queue:

use App\Jobs\Job1;
use App\Jobs\Job2;

// Dispatch Job1 to run on queue 'queue_name_1'
dispatch(new Job1())->onQueue('queue_name_1');

// Dispatch Job2 to run on queue 'queue_name_2' (or the default queue if not specified)
dispatch(new Job2())->withChain([
    new Job3()->onQueue('queue_name_3'), // Job3 will run on queue_name_3
]);

In the example above, Job1 will be dispatched and executed on the queue named queue_name_1. Job2 will be dispatched and executed on the default queue if not specified, but in this example, it is chained to Job3 which will be executed on the queue named queue_name_3.

To ensure that only the specified queue processes the jobs, you need to configure your queue worker to listen to that queue. You can do this by updating the .env file with the following configuration:

QUEUE_DRIVER=database
QUEUE_CONNECTION=sqlite

BROADCAST_DRIVER=log
CACHE_DRIVER=file
SESSION_DRIVER=file
SESSION_LIFETIME=120

# Database Queue Connection
QUEUE_QUEUES=queue_name_1,queue_name_2,queue_name_3

In the example above, the QUEUE_QUEUES configuration option is set to an array containing the names of the queues you want to listen to. In this case, the worker will listen to queue_name_1, queue_name_2, and queue_name_3.

Finally, you can start the queue worker with the following command:

php artisan queue:work --queue queue_name_1

This command will start the queue worker and only process jobs from the queue_name_1 queue. You can start other workers for other queues by using different commands with the appropriate queue name.