Queues
Queues
- Introduction
- Connections Vs. Queues
- Driver Notes & Prerequisites
- Creating Jobs
- Generating Job Classes
- Class Structure
- Unique Jobs
- Job Middleware
- Rate Limiting
- Preventing Job Overlaps
- Throttling Exceptions
- Dispatching Jobs
- Delayed Dispatching
- Synchronous Dispatching
- Jobs & Database Transactions
- Job Chaining
- Customizing The Queue & Connection
- Specifying Max Job Attempts / Timeout Values
- Error Handling
- Job Batching
- Defining Batchable Jobs
- Dispatching Batches
- Adding Jobs To Batches
- Inspecting Batches
- Cancelling Batches
- Batch Failures
- Pruning Batches
- Queueing Closures
- Running The Queue Worker
- The queue:work Command
- Queue Priorities
- Queue Workers & Deployment
- Job Expirations & Timeouts
- Supervisor Configuration
- Dealing With Failed Jobs
- Cleaning Up After Failed Jobs
- Retrying Failed Jobs
- Ignoring Missing Models
- Pruning Failed Jobs
- Storing Failed Jobs In DynamoDB
- Disabling Failed Job Storage
- Failed Job Events
- Clearing Jobs From Queues
- Monitoring Your Queues
- Testing
- Faking A Subset Of Jobs
- Testing Job Chains
- Testing Job Batches
- Job Events
Introduction
While building your web application, you may have some tasks, such as parsing and storing an uploaded CSV file, that take too long to perform during a typical web request. Thankfully, Laravel allows you to easily create queued jobs that may be processed in the background. By moving time intensive tasks to a queue, your application can respond to web requests with blazing speed and provide a better user experience to your customers.
Laravel queues provide a unified queueing API across a variety of different queue backends, such as Amazon SQS, Redis, or even a relational database.
Laravel’s queue configuration options are stored in your application’s config/queue.php configuration file. In this file, you will find connection configurations for each of the queue drivers that are included with the framework, including the database, Amazon SQS, Redis, and Beanstalkd drivers, as well as a synchronous driver that will execute jobs immediately (for use during local development). A null queue driver is also included which discards queued jobs.
Note
Laravel now offers Horizon, a beautiful dashboard and configuration system for your Redis powered queues. Check out the full Horizon documentation for more information.
Connections Vs. Queues
Before getting started with Laravel queues, it is important to understand the distinction between “connections” and “queues”. In your config/queue.php configuration file, there is a connections configuration array. This option defines the connections to backend queue services such as Amazon SQS, Beanstalk, or Redis. However, any given queue connection may have multiple “queues” which may be thought of as different stacks or piles of queued jobs.
Note that each connection configuration example in the queue configuration file contains a queue attribute. This is the default queue that jobs will be dispatched to when they are sent to a given connection. In other words, if you dispatch a job without explicitly defining which queue it should be dispatched to, the job will be placed on the queue that is defined in the queue attribute of the connection configuration:
use App\Jobs\ProcessPodcast; // This job is sent to the default connection's default queue...ProcessPodcast::dispatch(); // This job is sent to the default connection's "emails" queue...ProcessPodcast::dispatch()->onQueue('emails');
Some applications may not need to ever push jobs onto multiple queues, instead preferring to have one simple queue. However, pushing jobs to multiple queues can be especially useful for applications that wish to prioritize or segment how jobs are processed, since the Laravel queue worker allows you to specify which queues it should process by priority. For example, if you push jobs to a high queue, you may run a worker that gives them higher processing priority:
php artisan queue:work --queue=high,default
Driver Notes & Prerequisites
Database
In order to use the database queue driver, you will need a database table to hold the jobs. To generate a migration that creates this table, run the queue:table Artisan command. Once the migration has been created, you may migrate your database using the migrate command:
php artisan queue:table php artisan migrate
Finally, don’t forget to instruct your application to use the database driver by updating the QUEUE_CONNECTION variable in your application’s .env file:
QUEUE_CONNECTION=database
Redis
In order to use the redis queue driver, you should configure a Redis database connection in your config/database.php configuration file.
Redis Cluster
If your Redis queue connection uses a Redis Cluster, your queue names must contain a key hash tag. This is required in order to ensure all of the Redis keys for a given queue are placed into the same hash slot:
'redis' => [ 'driver' => 'redis', 'connection' => 'default', 'queue' => '{default}', 'retry_after' => 90,],
Blocking
When using the Redis queue, you may use the block_for configuration option to specify how long the driver should wait for a job to become available before iterating through the worker loop and re-polling the Redis database.
Adjusting this value based on your queue load can be more efficient than continually polling the Redis database for new jobs. For instance, you may set the value to 5 to indicate that the driver should block for five seconds while waiting for a job to become available:
'redis' => [ 'driver' => 'redis', 'connection' => 'default', 'queue' => 'default', 'retry_after' => 90, 'block_for' => 5,],
Warning
Settingblock_forto0will cause queue workers to block indefinitely until a job is available. This will also prevent signals such asSIGTERMfrom being handled until the next job has been processed.
Other Driver Prerequisites
The following dependencies are needed for the listed queue drivers. These dependencies may be installed via the Composer package manager:
- Amazon SQS:
aws/aws-sdk-php ~3.0 - Beanstalkd:
pda/pheanstalk ~4.0 - Redis:
predis/predis ~1.0or phpredis PHP extension
Creating Jobs
Generating Job Classes
By default, all of the queueable jobs for your application are stored in the app/Jobs directory. If the app/Jobs directory doesn’t exist, it will be created when you run the make:job Artisan command:
php artisan make:job ProcessPodcast
The generated class will implement the Illuminate\Contracts\Queue\ShouldQueue interface, indicating to Laravel that the job should be pushed onto the queue to run asynchronously.
Note
Job stubs may be customized using stub publishing.
Class Structure
Job classes are very simple, normally containing only a handle method that is invoked when the job is processed by the queue. To get started, let’s take a look at an example job class. In this example, we’ll pretend we manage a podcast publishing service and need to process the uploaded podcast files before they are published:
<?php namespace App\Jobs; use App\Models\Podcast;use App\Services\AudioProcessor;use Illuminate\Bus\Queueable;use Illuminate\Contracts\Queue\ShouldQueue;use Illuminate\Foundation\Bus\Dispatchable;use Illuminate\Queue\InteractsWithQueue;use Illuminate\Queue\SerializesModels; class ProcessPodcast implements ShouldQueue{ use Dispatchable, InteractsWithQueue, Queueable, SerializesModels; /** * Create a new job instance. */ public function __construct( public Podcast $podcast, ) {} /** * Execute the job. */ public function handle(AudioProcessor $processor): void { // Process uploaded podcast... }}
In this example, note that we were able to pass an Eloquent model directly into the queued job’s constructor. Because of the SerializesModels trait that the job is using, Eloquent models and their loaded relationships will be gracefully serialized and unserialized when the job is processing.
If your queued job accepts an Eloquent model in its constructor, only the identifier for the model will be serialized onto the queue. When the job is actually handled, the queue system will automatically re-retrieve the full model instance and its loaded relationships from the database. This approach to model serialization allows for much smaller job payloads to be sent to your queue driver.
handle Method Dependency Injection
The handle method is invoked when the job is processed by the queue. Note that we are able to type-hint dependencies on the handle method of the job. The Laravel service container automatically injects these dependencies.
If you would like to take total control over how the container injects dependencies into the handle method, you may use the container’s bindMethod method. The bindMethod method accepts a callback which receives the job and the container. Within the callback, you are free to invoke the handle method however you wish. Typically, you should call this method from the boot method of your App\Providers\AppServiceProvider service provider:
use App\Jobs\ProcessPodcast;use App\Services\AudioProcessor;use Illuminate\Contracts\Foundation\Application; $this->app->bindMethod([ProcessPodcast::class, 'handle'], function (ProcessPodcast $job, Application $app) { return $job->handle($app->make(AudioProcessor::class));});
Warning
Binary data, such as raw image contents, should be passed through thebase64_encodefunction before being passed to a queued job. Otherwise, the job may not properly serialize to JSON when being placed on the queue.
Queued Relationships
Because loaded relationships also get serialized, the serialized job string can sometimes become quite large. To prevent relations from being serialized, you can call the withoutRelations method on the model when setting a property value. This method will return an instance of the model without its loaded relationships:
/** * Create a new job instance. */public function __construct(Podcast $podcast){ $this->podcast = $podcast->withoutRelations();}
Furthermore, when a job is deserialized and model relationships are re-retrieved from the database, they will be retrieved in their entirety. Any previous relationship constraints that were applied before the model was serialized during the job queueing process will not be applied when the job is deserialized. Therefore, if you wish to work with a subset of a given relationship, you should re-constrain that relationship within your queued job.
Unique Jobs
Warning
Unique jobs require a cache driver that supports locks. Currently, thememcached,redis,dynamodb,database,file, andarraycache drivers support atomic locks. In addition, unique job constraints do not apply to jobs within batches.
Sometimes, you may want to ensure that only one instance of a specific job is on the queue at any point in time. You may do so by implementing the ShouldBeUnique interface on your job class. This interface does not require you to define any additional methods on your class:
<?php use Illuminate\Contracts\Queue\ShouldQueue;use Illuminate\Contracts\Queue\ShouldBeUnique; class UpdateSearchIndex implements ShouldQueue, ShouldBeUnique{ ...}
In the example above, the UpdateSearchIndex job is unique. So, the job will not be dispatched if another instance of the job is already on the queue and has not finished processing.
In certain cases, you may want to define a specific “key” that makes the job unique or you may want to specify a timeout beyond which the job no longer stays unique. To accomplish this, you may define uniqueId and uniqueFor properties or methods on your job class:
<?php use App\Product;use Illuminate\Contracts\Queue\ShouldQueue;use Illuminate\Contracts\Queue\ShouldBeUnique; class UpdateSearchIndex implements ShouldQueue, ShouldBeUnique{ /** * The product instance. * * @var \App\Product */ public $product; /** * The number of seconds after which the job's unique lock will be released. * * @var int */ public $uniqueFor = 3600; /** * The unique ID of the job. */ public function uniqueId(): string { return $this->product->id; }}
In the example above, the UpdateSearchIndex job is unique by a product ID. So, any new dispatches of the job with the same product ID will be ignored until the existing job has completed processing. In addition, if the existing job is not processed within one hour, the unique lock will be released and another job with the same unique key can be dispatched to the queue.
Warning
If your application dispatches jobs from multiple web servers or containers, you should ensure that all of your servers are communicating with the same central cache server so that Laravel can accurately determine if a job is unique.
Keeping Jobs Unique Until Processing Begins
By default, unique jobs are “unlocked” after a job completes processing or fails all of its retry attempts. However, there may be situations where you would like your job to unlock immediately before it is processed. To accomplish this, your job should implement the ShouldBeUniqueUntilProcessing contract instead of the ShouldBeUnique contract:
<?php use App\Product;use Illuminate\Contracts\Queue\ShouldQueue;use Illuminate\Contracts\Queue\ShouldBeUniqueUntilProcessing; class UpdateSearchIndex implements ShouldQueue, ShouldBeUniqueUntilProcessing{ // ...}
Unique Job Locks
Behind the scenes, when a ShouldBeUnique job is dispatched, Laravel attempts to acquire a lock with the uniqueId key. If the lock is not acquired, the job is not dispatched. This lock is released when the job completes processing or fails all of its retry attempts. By default, Laravel will use the default cache driver to obtain this lock. However, if you wish to use another driver for acquiring the lock, you may define a uniqueVia method that returns the cache driver that should be used:
use Illuminate\Contracts\Cache\Repository;use Illuminate\Support\Facades\Cache; class UpdateSearchIndex implements ShouldQueue, ShouldBeUnique{ ... /** * Get the cache driver for the unique job lock. */ public function uniqueVia(): Repository { return Cache::driver('redis'); }}
Note
If you only need to limit the concurrent processing of a job, use the WithoutOverlapping job middleware instead.
Job Middleware
Job middleware allow you to wrap custom logic around the execution of queued jobs, reducing boilerplate in the jobs themselves. For example, consider the following handle method which leverages Laravel’s Redis rate limiting features to allow only one job to process every five seconds:
use Illuminate\Support\Facades\Redis; /** * Execute the job. */public function handle(): void{ Redis::throttle('key')->block(0)->allow(1)->every(5)->then(function () { info('Lock obtained...'); // Handle job... }, function () { // Could not obtain lock... return $this->release(5); });}
While this code is valid, the implementation of the handle method becomes noisy since it is cluttered with Redis rate limiting logic. In addition, this rate limiting logic must be duplicated for any other jobs that we want to rate limit.
Instead of rate limiting in the handle method, we could define a job middleware that handles rate limiting. Laravel does not have a default location for job middleware, so you are welcome to place job middleware anywhere in your application. In this example, we will place the middleware in an app/Jobs/Middleware directory:
<?php namespace App\Jobs\Middleware; use Closure;use Illuminate\Support\Facades\Redis; class RateLimited{ /** * Process the queued job. * * @param \Closure(object): void $next */ public function handle(object $job, Closure $next): void { Redis::throttle('key') ->block(0)->allow(1)->every(5) ->then(function () use (object $job, Closure $next) { // Lock obtained... $next($job); }, function () use ($job) { // Could not obtain lock... $job->release(5); }); }}
As you can see, like route middleware, job middleware receive the job being processed and a callback that should be invoked to continue processing the job.
After creating job middleware, they may be attached to a job by returning them from the job’s middleware method. This method does not exist on jobs scaffolded by the make:job Artisan command, so you will need to manually add it to your job class:
use App\Jobs\Middleware\RateLimited; /** * Get the middleware the job should pass through. * * @return array<int, object> */public function middleware(): array{ return [new RateLimited];}
Note
Job middleware can also be assigned to queueable event listeners, mailables, and notifications.
Rate Limiting
Although we just demonstrated how to write your own rate limiting job middleware, Laravel actually includes a rate limiting middleware that you may utilize to rate limit jobs. Like route rate limiters, job rate limiters are defined using the RateLimiter facade’s for method.
For example, you may wish to allow users to backup their data once per hour while imposing no such limit on premium customers. To accomplish this, you may define a RateLimiter in the boot method of your AppServiceProvider:
use Illuminate\Cache\RateLimiting\Limit;use Illuminate\Support\Facades\RateLimiter; /** * Bootstrap any application services. */public function boot(): void{ RateLimiter::for('backups', function (object $job) { return $job->user->vipCustomer() ? Limit::none() : Limit::perHour(1)->by($job->user->id); });}
In the example above, we defined an hourly rate limit; however, you may easily define a rate limit based on minutes using the perMinute method. In addition, you may pass any value you wish to the by method of the rate limit; however, this value is most often used to segment rate limits by customer:
return Limit::perMinute(50)->by($job->user->id);
Once you have defined your rate limit, you may attach the rate limiter to your backup job using the Illuminate\Queue\Middleware\RateLimited middleware. Each time the job exceeds the rate limit, this middleware will release the job back to the queue with an appropriate delay based on the rate limit duration.
use Illuminate\Queue\Middleware\RateLimited; /** * Get the middleware the job should pass through. * * @return array<int, object> */public function middleware(): array{ return [new RateLimited('backups')];}
Releasing a rate limited job back onto the queue will still increment the job’s total number of attempts. You may wish to tune your tries and maxExceptions properties on your job class accordingly. Or, you may wish to use the retryUntil method to define the amount of time until the job should no longer be attempted.
If you do not want a job to be retried when it is rate limited, you may use the dontRelease method:
/** * Get the middleware the job should pass through. * * @return array<int, object> */public function middleware(): array{ return [(new RateLimited('backups'))->dontRelease()];}
Note
If you are using Redis, you may use theIlluminate\Queue\Middleware\RateLimitedWithRedismiddleware, which is fine-tuned for Redis and more efficient than the basic rate limiting middleware.
Preventing Job Overlaps
Laravel includes an Illuminate\Queue\Middleware\WithoutOverlapping middleware that allows you to prevent job overlaps based on an arbitrary key. This can be helpful when a queued job is modifying a resource that should only be modified by one job at a time.
For example, let’s imagine you have a queued job that updates a user’s credit score and you want to prevent credit score update job overlaps for the same user ID. To accomplish this, you can return the WithoutOverlapping middleware from your job’s middleware method:
use Illuminate\Queue\Middleware\WithoutOverlapping; /** * Get the middleware the job should pass through. * * @return array<int, object> */public function middleware(): array{ return [new WithoutOverlapping($this->user->id)];}
Any overlapping jobs of the same type will be released back to the queue. You may also specify the number of seconds that must elapse before the released job will be attempted again:
/** * Get the middleware the job should pass through. * * @return array<int, object> */public function middleware(): array{ return [(new WithoutOverlapping($this->order->id))->releaseAfter(60)];}
If you wish to immediately delete any overlapping jobs so that they will not be retried, you may use the dontRelease method:
/** * Get the middleware the job should pass through. * * @return array<int, object> */public function middleware(): array{ return [(new WithoutOverlapping($this->order->id))->dontRelease()];}
The WithoutOverlapping middleware is powered by Laravel’s atomic lock feature. Sometimes, your job may unexpectedly fail or timeout in such a way that the lock is not released. Therefore, you may explicitly define a lock expiration time using the expireAfter method. For example, the example below will instruct Laravel to release the WithoutOverlapping lock three minutes after the job has started processing:
/** * Get the middleware the job should pass through. * * @return array<int, object> */public function middleware(): array{ return [(new WithoutOverlapping($this->order->id))->expireAfter(180)];}
Warning The
WithoutOverlappingmiddleware requires a cache driver that supports locks. Currently, thememcached,redis,dynamodb,database,file, andarraycache drivers support atomic locks.
Sharing Lock Keys Across Job Classes
By default, the WithoutOverlapping middleware will only prevent overlapping jobs of the same class. So, although two different job classes may use the same lock key, they will not be prevented from overlapping. However, you can instruct Laravel to apply the key across job classes using the shared method:
use Illuminate\Queue\Middleware\WithoutOverlapping; class ProviderIsDown{ // ... public function middleware(): array { return [ (new WithoutOverlapping("status:{$this->provider}"))->shared(), ]; }} class ProviderIsUp{ // ... public function middleware(): array { return [ (new WithoutOverlapping("status:{$this->provider}"))->shared(), ]; }}
Throttling Exceptions
Laravel includes a Illuminate\Queue\Middleware\ThrottlesExceptions middleware that allows you to throttle exceptions. Once the job throws a given number of exceptions, all further attempts to execute the job are delayed until a specified time interval lapses. This middleware is particularly useful for jobs that interact with third-party services that are unstable.
For example, let’s imagine a queued job that interacts with a third-party API that begins throwing exceptions. To throttle exceptions, you can return the ThrottlesExceptions middleware from your job’s middleware method. Typically, this middleware should be paired with a job that implements time based attempts:
use DateTime;use Illuminate\Queue\Middleware\ThrottlesExceptions; /** * Get the middleware the job should pass through. * * @return array<int, object> */public function middleware(): array{ return [new ThrottlesExceptions(10, 5)];} /** * Determine the time at which the job should timeout. */public function retryUntil(): DateTime{ return now()->addMinutes(5);}
The first constructor argument accepted by the middleware is the number of exceptions the job can throw before being throttled, while the second constructor argument is the number of minutes that should elapse before the job is attempted again once it has been throttled. In the code example above, if the job throws 10 exceptions within 5 minutes, we will wait 5 minutes before attempting the job again.
When a job throws an exception but the exception threshold has not yet been reached, the job will typically be retried immediately. However, you may specify the number of minutes such a job should be delayed by calling the backoff method when attaching the middleware to the job:
use Illuminate\Queue\Middleware\ThrottlesExceptions; /** * Get the middleware the job should pass through. * * @return array<int, object> */public function middleware(): array{ return [(new ThrottlesExceptions(10, 5))->backoff(5)];}
Internally, this middleware uses Laravel’s cache system to implement rate limiting, and the job’s class name is utilized as the cache “key”. You may override this key by calling the by method when attaching the middleware to your job. This may be useful if you have multiple jobs interacting with the same third-party service and you would like them to share a common throttling “bucket”:
use Illuminate\Queue\Middleware\ThrottlesExceptions; /** * Get the middleware the job should pass through. * * @return array<int, object> */public function middleware(): array{ return [(new ThrottlesExceptions(10, 10))->by('key')];}
Note
If you are using Redis, you may use theIlluminate\Queue\Middleware\ThrottlesExceptionsWithRedismiddleware, which is fine-tuned for Redis and more efficient than the basic exception throttling middleware.
Dispatching Jobs
Once you have written your job class, you may dispatch it using the dispatch method on the job itself. The arguments passed to the dispatch method will be given to the job’s constructor:
<?php namespace App\Http\Controllers; use App\Http\Controllers\Controller;use App\Jobs\ProcessPodcast;use App\Models\Podcast;use Illuminate\Http\RedirectResponse;use Illuminate\Http\Request; class PodcastController extends Controller{ /** * Store a new podcast. */ public function store(Request $request): RedirectResponse { $podcast = Podcast::create(/* ... */); // ... ProcessPodcast::dispatch($podcast); return redirect('/podcasts'); }}
If you would like to conditionally dispatch a job, you may use the dispatchIf and dispatchUnless methods:
ProcessPodcast::dispatchIf($accountActive, $podcast); ProcessPodcast::dispatchUnless($accountSuspended, $podcast);
In new Laravel applications, the sync driver is the default queue driver. This driver executes jobs synchronously in the foreground of the current request, which is often convenient during local development. If you would like to actually begin queueing jobs for background processing, you may specify a different queue driver within your application’s config/queue.php configuration file.
Delayed Dispatching
If you would like to specify that a job should not be immediately available for processing by a queue worker, you may use the delay method when dispatching the job. For example, let’s specify that a job should not be available for processing until 10 minutes after it has been dispatched:
<?php namespace App\Http\Controllers; use App\Http\Controllers\Controller;use App\Jobs\ProcessPodcast;use App\Models\Podcast;use Illuminate\Http\RedirectResponse;use Illuminate\Http\Request; class PodcastController extends Controller{ /** * Store a new podcast. */ public function store(Request $request): RedirectResponse { $podcast = Podcast::create(/* ... */); // ... ProcessPodcast::dispatch($podcast) ->delay(now()->addMinutes(10)); return redirect('/podcasts'); }}
Warning
The Amazon SQS queue service has a maximum delay time of 15 minutes.
Dispatching After The Response Is Sent To Browser
Alternatively, the dispatchAfterResponse method delays dispatching a job until after the HTTP response is sent to the user’s browser if your web server is using FastCGI. This will still allow the user to begin using the application even though a queued job is still executing. This should typically only be used for jobs that take about a second, such as sending an email. Since they are processed within the current HTTP request, jobs dispatched in this fashion do not require a queue worker to be running in order for them to be processed:
use App\Jobs\SendNotification; SendNotification::dispatchAfterResponse();
You may also dispatch a closure and chain the afterResponse method onto the dispatch helper to execute a closure after the HTTP response has been sent to the browser:
use App\Mail\WelcomeMessage;use Illuminate\Support\Facades\Mail; dispatch(function () { Mail::to('[email protected]')->send(new WelcomeMessage);})->afterResponse();
Synchronous Dispatching
If you would like to dispatch a job immediately (synchronously), you may use the dispatchSync method. When using this method, the job will not be queued and will be executed immediately within the current process:
<?php namespace App\Http\Controllers; use App\Http\Controllers\Controller;use App\Jobs\ProcessPodcast;use App\Models\Podcast;use Illuminate\Http\RedirectResponse;use Illuminate\Http\Request; class PodcastController extends Controller{ /** * Store a new podcast. */ public function store(Request $request): RedirectResponse { $podcast = Podcast::create(/* ... */); // Create podcast... ProcessPodcast::dispatchSync($podcast); return redirect('/podcasts'); }}
Jobs & Database Transactions
While it is perfectly fine to dispatch jobs within database transactions, you should take special care to ensure that your job will actually be able to execute successfully. When dispatching a job within a transaction, it is possible that the job will be processed by a worker before the parent transaction has committed. When this happens, any updates you have made to models or database records during the database transaction(s) may not yet be reflected in the database. In addition, any models or database records created within the transaction(s) may not exist in the database.
Thankfully, Laravel provides several methods of working around this problem. First, you may set the after_commit connection option in your queue connection’s configuration array:
'redis' => [ 'driver' => 'redis', // ... 'after_commit' => true,],
When the after_commit option is true, you may dispatch jobs within database transactions; however, Laravel will wait until the open parent database transactions have been committed before actually dispatching the job. Of course, if no database transactions are currently open, the job will be dispatched immediately.
If a transaction is rolled back due to an exception that occurs during the transaction, the jobs that were dispatched during that transaction will be discarded.
Note
Setting theafter_commitconfiguration option totruewill also cause any queued event listeners, mailables, notifications, and broadcast events to be dispatched after all open database transactions have been committed.
Specifying Commit Dispatch Behavior Inline
If you do not set the after_commit queue connection configuration option to true, you may still indicate that a specific job should be dispatched after all open database transactions have been committed. To accomplish this, you may chain the afterCommit method onto your dispatch operation:
use App\Jobs\ProcessPodcast; ProcessPodcast::dispatch($podcast)->afterCommit();
Likewise, if the after_commit configuration option is set to true, you may indicate that a specific job should be dispatched immediately without waiting for any open database transactions to commit:
ProcessPodcast::dispatch($podcast)->beforeCommit();
Job Chaining
Job chaining allows you to specify a list of queued jobs that should be run in sequence after the primary job has executed successfully. If one job in the sequence fails, the rest of the jobs will not be run. To execute a queued job chain, you may use the chain method provided by the Bus facade. Laravel’s command bus is a lower level component that queued job dispatching is built on top of:
use App\Jobs\OptimizePodcast;use App\Jobs\ProcessPodcast;use App\Jobs\ReleasePodcast;use Illuminate\Support\Facades\Bus; Bus::chain([ new ProcessPodcast, new OptimizePodcast, new ReleasePodcast,])->dispatch();
In addition to chaining job class instances, you may also chain closures:
Bus::chain([ new ProcessPodcast, new OptimizePodcast, function () { Podcast::update(/* ... */); },])->dispatch();
Warning
Deleting jobs using the$this->delete()method within the job will not prevent chained jobs from being processed. The chain will only stop executing if a job in the chain fails.
Chain Connection & Queue
If you would like to specify the connection and queue that should be used for the chained jobs, you may use the onConnection and onQueue methods. These methods specify the queue connection and queue name that should be used unless the queued job is explicitly assigned a different connection / queue:
Bus::chain([ new ProcessPodcast, new OptimizePodcast, new ReleasePodcast,])->onConnection('redis')->onQueue('podcasts')->dispatch();
Chain Failures
When chaining jobs, you may use the catch method to specify a closure that should be invoked if a job within the chain fails. The given callback will receive the Throwable instance that caused the job failure:
use Illuminate\Support\Facades\Bus;use Throwable; Bus::chain([ new ProcessPodcast, new OptimizePodcast, new ReleasePodcast,])->catch(function (Throwable $e) { // A job within the chain has failed...})->dispatch();
Warning
Since chain callbacks are serialized and executed at a later time by the Laravel queue, you should not use the$thisvariable within chain callbacks.
Customizing The Queue & Connection
Dispatching To A Particular Queue
By pushing jobs to different queues, you may “categorize” your queued jobs and even prioritize how many workers you assign to various queues. Keep in mind, this does not push jobs to different queue “connections” as defined by your queue configuration file, but only to specific queues within a single connection. To specify the queue, use the onQueue method when dispatching the job:
<?php namespace App\Http\Controllers; use App\Http\Controllers\Controller;use App\Jobs\ProcessPodcast;use App\Models\Podcast;use Illuminate\Http\RedirectResponse;use Illuminate\Http\Request; class PodcastController extends Controller{ /** * Store a new podcast. */ public function store(Request $request): RedirectResponse { $podcast = Podcast::create(/* ... */); // Create podcast... ProcessPodcast::dispatch($podcast)->onQueue('processing'); return redirect('/podcasts'); }}
Alternatively, you may specify the job’s queue by calling the onQueue method within the job’s constructor:
<?php namespace App\Jobs; use Illuminate\Bus\Queueable; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Foundation\Bus\Dispatchable; use Illuminate\Queue\InteractsWithQueue; use Illuminate\Queue\SerializesModels; class ProcessPodcast implements ShouldQueue{ use Dispatchable, InteractsWithQueue, Queueable, SerializesModels; /** * Create a new job instance. */ public function __construct() { $this->onQueue('processing'); }}
Dispatching To A Particular Connection
If your application interacts with multiple queue connections, you may specify which connection to push a job to using the onConnection method:
<?php namespace App\Http\Controllers; use App\Http\Controllers\Controller;use App\Jobs\ProcessPodcast;use App\Models\Podcast;use Illuminate\Http\RedirectResponse;use Illuminate\Http\Request; class PodcastController extends Controller{ /** * Store a new podcast. */ public function store(Request $request): RedirectResponse { $podcast = Podcast::create(/* ... */); // Create podcast... ProcessPodcast::dispatch($podcast)->onConnection('sqs'); return redirect('/podcasts'); }}
You may chain the onConnection and onQueue methods together to specify the connection and the queue for a job:
ProcessPodcast::dispatch($podcast) ->onConnection('sqs') ->onQueue('processing');
Alternatively, you may specify the job’s connection by calling the onConnection method within the job’s constructor:
<?php namespace App\Jobs; use Illuminate\Bus\Queueable; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Foundation\Bus\Dispatchable; use Illuminate\Queue\InteractsWithQueue; use Illuminate\Queue\SerializesModels; class ProcessPodcast implements ShouldQueue{ use Dispatchable, InteractsWithQueue, Queueable, SerializesModels; /** * Create a new job instance. */ public function __construct() { $this->onConnection('sqs'); }}
Specifying Max Job Attempts / Timeout Values
Max Attempts
If one of your queued jobs is encountering an error, you likely do not want it to keep retrying indefinitely. Therefore, Laravel provides various ways to specify how many times or for how long a job may be attempted.
One approach to specifying the maximum number of times a job may be attempted is via the --tries switch on the Artisan command line. This will apply to all jobs processed by the worker unless the job being processed specifies the number of times it may be attempted:
php artisan queue:work --tries=3
If a job exceeds its maximum number of attempts, it will be considered a “failed” job. For more information on handling failed jobs, consult the failed job documentation. If --tries=0 is provided to the queue:work command, the job will retried indefinitely.
You may take a more granular approach by defining the maximum number of times a job may be attempted on the job class itself. If the maximum number of attempts is specified on the job, it will take precedence over the --tries value provided on the command line:
<?php namespace App\Jobs; class ProcessPodcast implements ShouldQueue{ /** * The number of times the job may be attempted. * * @var int */ public $tries = 5;}
Time Based Attempts
As an alternative to defining how many times a job may be attempted before it fails, you may define a time at which the job should no longer be attempted. This allows a job to be attempted any number of times within a given time frame. To define the time at which a job should no longer be attempted, add a retryUntil method to your job class. This method should return a DateTime instance:
use DateTime; /** * Determine the time at which the job should timeout. */public function retryUntil(): DateTime{ return now()->addMinutes(10);}
Note
You may also define atriesproperty orretryUntilmethod on your queued event listeners.
Max Exceptions
Sometimes you may wish to specify that a job may be attempted many times, but should fail if the retries are triggered by a given number of unhandled exceptions (as opposed to being released by the release method directly). To accomplish this, you may define a maxExceptions property on your job class:
<?php namespace App\Jobs; use Illuminate\Support\Facades\Redis; class ProcessPodcast implements ShouldQueue{ /** * The number of times the job may be attempted. * * @var int */ public $tries = 25; /** * The maximum number of unhandled exceptions to allow before failing. * * @var int */ public $maxExceptions = 3; /** * Execute the job. */ public function handle(): void { Redis::throttle('key')->allow(10)->every(60)->then(function () { // Lock obtained, process the podcast... }, function () { // Unable to obtain lock... return $this->release(10); }); }}
In this example, the job is released for ten seconds if the application is unable to obtain a Redis lock and will continue to be retried up to 25 times. However, the job will fail if three unhandled exceptions are thrown by the job.
Timeout
Warning
ThepcntlPHP extension must be installed in order to specify job timeouts.
Often, you know roughly how long you expect your queued jobs to take. For this reason, Laravel allows you to specify a “timeout” value. By default, the timeout value is 60 seconds. If a job is processing for longer than the number of seconds specified by the timeout value, the worker processing the job will exit with an error. Typically, the worker will be restarted automatically by a process manager configured on your server.
The maximum number of seconds that jobs can run may be specified using the --timeout switch on the Artisan command line:
php artisan queue:work --timeout=30
If the job exceeds its maximum attempts by continually timing out, it will be marked as failed.
You may also define the maximum number of seconds a job should be allowed to run on the job class itself. If the timeout is specified on the job, it will take precedence over any timeout specified on the command line:
<?php namespace App\Jobs; class ProcessPodcast implements ShouldQueue{ /** * The number of seconds the job can run before timing out. * * @var int */ public $timeout = 120;}
Sometimes, IO blocking processes such as sockets or outgoing HTTP connections may not respect your specified timeout. Therefore, when using these features, you should always attempt to specify a timeout using their APIs as well. For example, when using Guzzle, you should always specify a connection and request timeout value.
Failing On Timeout
If you would like to indicate that a job should be marked as failed on timeout, you may define the $failOnTimeout property on the job class:
/** * Indicate if the job should be marked as failed on timeout. * * @var bool */public $failOnTimeout = true;
(本文超出站点单文档体积上限,已按小节截断)
