To set up a queue worker in Laravel, follow these steps:
Step 1: Create the Required Tables
1. Create the Jobs Table:
- Run the following command to create the necessary table for storing jobs:
bash
php artisan queue:table
- Then, migrate the table:
bash
php artisan migrate
Step 2: Generate the Job Class
1. Generate the Job Class:
- Create a new job class using the following command:
bash
php artisan make:job SendNotification
- This will generate a new PHP file in the `app/Jobs` directory.
Step 3: Configure the Queue Driver
1. Configure the Queue Driver:
- In your `.env` file, set the `QUEUE_DRIVER` or `QUEUE_CONNECTION` to the desired queue backend. For example, to use the database as the queue driver:
makefile
QUEUE_DRIVER=database
Step 4: Run the Queue Worker
1. Run the Queue Worker:
- You can run the queue worker using the `queue:work` command. This command will process new jobs as they are pushed onto the queue:
bash
php artisan queue:work
- Alternatively, you can use the `queue:listen` command, which will continuously listen for new jobs and process them:
bash
php artisan queue:listen
Step 5: Configure Supervisor (Optional)
1. Configure Supervisor (Optional):
- If you want the queue worker to run permanently in the background, you can use a process monitor like Supervisor. This ensures that the queue worker does not stop running even if your terminal is closed.
- Install Supervisor:
bash
apt install supervisor
- Create a supervisor configuration file:
bash
cd /etc/supervisor/conf.d
nano queue-worker.conf
- Add the following configuration:
makefile
[program:queue-worker]
process_name = %(program_name)s_%(process_num)02d
command=php /var/www/html/project-folder/artisan queue:listen
autostart=true
autorestart=true
user=root
numprocs=1
redirect_stderr=true
stdout_logfile=/var/www/html/project-folder/public/worker.log
Step 6: Restart Supervisor
1. Restart Supervisor:
- Reread the supervisor configuration:
bash
supervisorctl reread
- Update the supervisor configuration:
bash
supervisorctl update
Additional Tips
- Restart Queue Workers:
- If you make changes to your code, you need to restart the queue workers to ensure they pick up the changes. You can do this by running:
bash
php artisan queue:restart
- Error Handling:
- Make sure to handle errors in your job classes by implementing the `failed` method. This method will be called if a job fails to execute.
- Monitoring:
- Use tools like Laravel Horizon or Laravel Telescope to monitor your queue workers and jobs. These tools provide detailed insights into the performance and health of your queue workers[1][2][3][4][5].Citations:
[1] https://forge.laravel.com/docs/sites/queues.html
[2] https://dev.to/techparida/how-to-set-up-laravel-queues-on-production-4one
[3] https://laravel.com/docs/5.8/queues
[4] https://laravel.com/docs/11.x/queues
[5] https://www.honeybadger.io/blog/job-queues-and-workers-in-laravel-apps/