How to Run Queue Worker in Laravel: Simple Guide
To run a queue worker in Laravel, use the
php artisan queue:work command in your terminal. This command listens for new jobs on the queue and processes them automatically.Syntax
The basic syntax to run a queue worker in Laravel is:
php artisan queue:work [connection] [--queue=queue_name] [--once] [--delay=seconds] [--sleep=seconds] [--tries=number]Here’s what each part means:
connection: Optional. The name of the queue connection to use (default is usuallysync,database, orredis).--queue: Specify which queue to listen to if you have multiple queues.--once: Process only the next job and then stop.--delay: Delay failed jobs for the given seconds before retrying.--sleep: Number of seconds to wait before checking for new jobs if none are available.--tries: Number of times to attempt a job before marking it as failed.
bash
php artisan queue:work
php artisan queue:work redis --queue=emails --tries=3Example
This example shows how to start a queue worker that listens on the default connection and processes jobs continuously.
bash
php artisan queue:work
Output
[2024-06-01 12:00:00] Processing: App\Jobs\SendWelcomeEmail
[2024-06-01 12:00:01] Processed: App\Jobs\SendWelcomeEmail
Common Pitfalls
Some common mistakes when running Laravel queue workers include:
- Not running the queue worker as a background process, causing it to stop when the terminal closes.
- Forgetting to configure the queue connection properly in
config/queue.php. - Not setting up a supervisor or process manager to keep the worker running continuously in production.
- Using
queue:listeninstead ofqueue:work, which is less efficient.
bash
Wrong way: php artisan queue:listen Right way: php artisan queue:work
Quick Reference
| Command | Description |
|---|---|
| php artisan queue:work | Start processing jobs on the default queue connection |
| php artisan queue:work redis --queue=emails | Process jobs from the 'emails' queue on Redis connection |
| php artisan queue:work --once | Process only the next job and then stop |
| php artisan queue:work --tries=5 | Try each job 5 times before failing |
| php artisan queue:restart | Restart all queue workers gracefully |
Key Takeaways
Use
php artisan queue:work to start a Laravel queue worker.Configure your queue connection correctly in
config/queue.php before running workers.Run queue workers as background processes or use a process manager like Supervisor in production.
Avoid using
queue:listen as it is less efficient than queue:work.Use options like
--queue, --tries, and --once to control worker behavior.