Table of Contents
✅ 1. Configure the Queue Driver
✅ 2. Create a Job (Optional but Common)
✅ 3. Set Up the Queue Table (if using database driver)
✅ 4. Start the Queue Worker
Useful options:
✅ 5. Keep the Worker Running (Supervision)
Install Supervisor (Ubuntu/Debian):
Create a Supervisor config:
✅ 6. Dispatch Jobs from Your Code
✅ 7. Monitor and Retry Failed Jobs
Summary
Home PHP Framework Laravel How to set up a queue worker in Laravel?

How to set up a queue worker in Laravel?

Aug 06, 2025 pm 12:19 PM

Configure queue driver: Set QUEUE_CONNECTION to database or redis in the .env file; 2. Create task class: Use php artisan make:job to generate tasks that implement the ShouldQueue interface; 3. Set database tables: Run php artisan queue:table and migrate to create jobs tables; 4. Start queue worker: execute php artisan queue:work and add --tries, --delay and other parameters to control retry and delay; 5. Use Supervisor to keep running: Configure Supervisor to ensure that the worker continues to run and restart regularly to avoid memory leaks; 6. Distribute tasks from the code: push tasks through the Job::dispatch() or delay() method; 7. Monitor and retry failed tasks: Generate failed_jobs table, and use queue:failed, queue:retry and queue:flush to manage failed tasks; after completing the above steps, the Laravel queue system can handle tasks asynchronously.

How to set up a queue worker in Laravel?

Setting up a queue worker in Laravel is straightforward once you understand the basics of Laravel's queue system. Here's how to do it step by step.

How to set up a queue worker in Laravel?

✅ 1. Configure the Queue Driver

First, decide which queue driver you want to use. Laravel supports several: sync (default, runs jobs immediately), database , redis , sqs , etc.

Open your .env file and change the QUEUE_CONNECTION :

How to set up a queue worker in Laravel?
 QUEUE_CONNECTION=database

Or for Redis:

 QUEUE_CONNECTION=redis

? For local development, database is a good choice. For production, redis or sqs are more performant.

How to set up a queue worker in Laravel?

Then, make sure the corresponding config in config/queue.php is set up correctly.


✅ 2. Create a Job (Optional but Common)

Generate a queued job using Artisan:

 php artisan make:job ProcessPodcast

This creates a class in app/Jobs/ProcessPodcast.php . You can dispatch it like:

 ProcessPodcast::dispatch($podcast);

Make sure your job implements ShouldQueue (the generated job does this by default).


✅ 3. Set Up the Queue Table (if using database driver)

If you're using the database driver, create the jobs table:

 php artisan queue:table

Run the migration:

 php artisan migrate

This creates the jobs table where queued jobs are stored.


✅ 4. Start the Queue Worker

Run the queue worker with:

 php artisan queue:work

This starts a worker that listens for new jobs and processes them.

Useful options:

  • --queue=high,low – process specific queues
  • --delay=5 – delay failed jobs by 5 seconds
  • --tries=3 – retry failed jobs up to 3 times
  • --timeout=60 – job timeout in seconds

Example:

 php artisan queue:work --tries=3 --delay=2

✅ 5. Keep the Worker Running (Supervision)

The queue:work command should run continuously in production. Use a process monitor like Supervisor .

Install Supervisor (Ubuntu/Debian):

 sudo apt install supervisor

Create a Supervisor config:

/etc/supervisor/conf.d/laravel-worker.conf

 [program:laravel-worker]
process_name=%(program_name)s_%(process_num)02d
command=php /var/www/your-app/artisan queue:work --sleep=3 --tries=3 --max-time=3600
autostart=true
autorestart=true
user=www-data
redirect_stderr=true
stdout_logfile=/var/www/your-app/storage/logs/worker.log
stopwaitsecs=3600

⚠️ Note: --max-time=3600 restarts the worker after 1 hour to avoid memory leaks.

Then reload Supervisor:

 sudo supervisorctl read
sudo supervisorctl update
sudo supervisorctl start laravel-worker:*

✅ 6. Dispatch Jobs from Your Code

From a controller or service:

 use App\Jobs\ProcessPodcast;

ProcessPodcast::dispatch($podcast);

Or with delayed dispatch:

 ProcessPodcast::dispatch($podcast)->delay(now()->addMinutes(10));

✅ 7. Monitor and Retry Failed Jobs

Laravel logs failed jobs in the failed_jobs table. To create it:

 php artisan queue:failed-table
php artisan migrate

To log failed jobs:

 php artisan queue:work --log-failed

View failed jobs:

 php artisan queue:failed

Retry them:

 php artisan queue:retry all

Or remove:

 php artisan queue:flush

Summary

  • Choose and configure a queue driver.
  • Set up the database table if needed.
  • Create jobs and dispatch them.
  • Run queue:work and use Supervisor to keep it alive.
  • Handle failures and logging.

You're now processing jobs asynchronously. Basically, that's all it takes — not complex, but easy to miss a step.

The above is the detailed content of How to set up a queue worker in Laravel?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

PHP Tutorial
1510
276
What is Configuration Caching in Laravel? What is Configuration Caching in Laravel? Jul 27, 2025 am 03:54 AM

Laravel's configuration cache improves performance by merging all configuration files into a single cache file. Enabling configuration cache in a production environment can reduce I/O operations and file parsing on each request, thereby speeding up configuration loading; 1. It should be enabled when the application is deployed, the configuration is stable and no frequent changes are required; 2. After enabling, modify the configuration, you need to re-run phpartisanconfig:cache to take effect; 3. Avoid using dynamic logic or closures that depend on runtime conditions in the configuration file; 4. When troubleshooting problems, you should first clear the cache, check the .env variables and re-cache.

Generating URLs for Named Routes in Laravel. Generating URLs for Named Routes in Laravel. Jul 16, 2025 am 02:50 AM

The most common way to generate a named route in Laravel is to use the route() helper function, which automatically matches the path based on the route name and handles parameter binding. 1. Pass the route name and parameters in the controller or view, such as route('user.profile',['id'=>1]); 2. When multiple parameters, you only need to pass the array, and the order does not affect the matching, such as route('user.post.show',['id'=>1,'postId'=>10]); 3. Links can be directly embedded in the Blade template, such as viewing information; 4. When optional parameters are not provided, they are not displayed, such as route('user.post',

Handling HTTP Requests and Responses in Laravel. Handling HTTP Requests and Responses in Laravel. Jul 16, 2025 am 03:21 AM

The core of handling HTTP requests and responses in Laravel is to master the acquisition of request data, response return and file upload. 1. When receiving request data, you can inject the Request instance through type prompts and use input() or magic methods to obtain fields, and combine validate() or form request classes for verification; 2. Return response supports strings, views, JSON, responses with status codes and headers and redirect operations; 3. When processing file uploads, you need to use the file() method and store() to store files. Before uploading, you should verify the file type and size, and the storage path can be saved to the database.

Explain Laravel Eloquent Scopes. Explain Laravel Eloquent Scopes. Jul 26, 2025 am 07:22 AM

Laravel's EloquentScopes is a tool that encapsulates common query logic, divided into local scope and global scope. 1. The local scope is defined with a method starting with scope and needs to be called explicitly, such as Post::published(); 2. The global scope is automatically applied to all queries, often used for soft deletion or multi-tenant systems, and the Scope interface needs to be implemented and registered in the model; 3. The scope can be equipped with parameters, such as filtering articles by year or month, and corresponding parameters are passed in when calling; 4. Pay attention to naming specifications, chain calls, temporary disabling and combination expansion when using to improve code clarity and reusability.

How to perform Request Validation in Laravel? How to perform Request Validation in Laravel? Jul 16, 2025 am 03:03 AM

There are two main methods for request verification in Laravel: controller verification and form request classes. 1. The validate() method in the controller is suitable for simple scenarios, directly passing in rules and automatically returning errors; 2. The FormRequest class is suitable for complex or reusable scenarios, creating classes through Artisan and defining rules in rules() to achieve code decoupling and reusing; 3. The error prompts can be customized through messages() to improve user experience; 4. Defining field alias through attributes() to make the error message more friendly; the two methods have their advantages and disadvantages, and the appropriate solution should be selected according to project needs.

Generating and using database factories in Laravel. Generating and using database factories in Laravel. Jul 16, 2025 am 02:05 AM

Database Factory is a tool in Laravel for generating model fake data. It quickly creates the data required for testing or development by defining field rules. For example, after using phpartisanmake:factory to generate factory files, sets the generation logic of fields such as name and email in the definition() method, and creates records through User::factory()->create(); 1. Supports batch generation of data, such as User::factory(10)->create(); 2. Use make() to generate uninvented data arrays; 3. Allows temporary overwriting of field values; 4. Supports association relationships, such as automatic creation

Using the Translator facade for Localization in Laravel. Using the Translator facade for Localization in Laravel. Jul 21, 2025 am 01:06 AM

TheTranslatorfacadeinLaravelisusedforlocalizationbyfetchingtranslatedstringsandswitchinglanguagesatruntime.Touseit,storetranslationstringsinlanguagefilesunderthelangdirectory(e.g.,en,es,fr),thenretrievethemviaLang::get()orthe__()helperfunction,suchas

How to mock objects in Laravel tests? How to mock objects in Laravel tests? Jul 27, 2025 am 03:13 AM

UseMockeryforcustomdependenciesbysettingexpectationswithshouldReceive().2.UseLaravel’sfake()methodforfacadeslikeMail,Queue,andHttptopreventrealinteractions.3.Replacecontainer-boundserviceswith$this->mock()forcleanersyntax.4.UseHttp::fake()withURLp

See all articles