Expand description
Queues: jobs that run later, outside the request that dispatched them.
Some work, such as transcoding an uploaded podcast or sending a thousand emails, takes too long to do while a request waits. This module lets you push that work to a queue and run it in a worker process. To learn more, check out the queues guide.
A job is a Queueable struct with #[job] on its impl
block. Dispatching the job pushes it to a connection, and the connection keeps the job until a
worker runs it:
use laravel::container::Inject;
use laravel::queue::job;
#[derive(laravel::queue::Queueable)]
pub struct ProcessPodcast {
pub podcast_id: i64,
}
#[job(
queue = "podcasts",
tries = 3,
backoff = [10.seconds(), 1.minutes()],
timeout = 2.minutes(),
)]
impl ProcessPodcast {
async fn handle(self, audio: Inject<AudioProcessor>) -> laravel::Result<()> {
audio.process(self.podcast_id).await
}
}
ProcessPodcast { podcast_id: 42 }.dispatch().await?;config.queue names the application’s connections. Each connection uses the database,
redis, sqs, cloud, sync, or discard driver, or a driver that an application or
package registered with Drivers::extend. Laravel creates a connection’s driver the first
time a job is pushed to the connection or a worker starts working it.
§Running jobs
Each job runs in a fresh application context that starts with the dispatching context’s
values. Values that the job adds to its context carry on to its error reports, its failed
hook, the worker’s events about the job, the callbacks the job triggers, and the next job in
its chain. The job’s log lines carry a job span with its ID, name, connection, queue, and
attempt number.
Before each run, the worker checks whether the job may still run. If the job’s retry_for has
passed, or the job has no retry_for and has already run tries times, the worker fails the
job for good without running it.
When a run fails, the worker fails the job for good if the job called Attempt::fail, the
job can’t be decoded, the run was the job’s last, or the run used up the job’s max_errors.
Otherwise, the worker retries the job after the backoff for that run’s number. A release also
uses up a run, so a retry after a release waits as long as it would after a failed run.
When a job fails for good, the worker removes it from its queue and stores it with the failed
jobs. Then the job’s failed hook runs, the worker dispatches events::JobFailed, and the
worker reports the job’s error. A job that can’t be decoded doesn’t run its failed hook or
dispatch events.
queue:retry pushes a failed job back onto its queue with the same ID, all of its tries, and
a fresh retry_for. When the retried job succeeds, its chain continues, and its batch stops
counting it as failed. A retried job on an SQS FIFO queue gets a new deduplication ID.
§Workers
queue:work fails for the sync and discard connections. When a connection’s backend is
unavailable, the worker reports the error and tries again, doubling its wait each time up to a
minute. A worker started with --stop-when-empty exits with status 1 instead.
When a worker is killed, its jobs stay reserved until their reservations lapse, about a minute
later. The interrupted run counts as an attempt and as an error toward max_errors.
queue:restart and queue:pause reach workers through the default cache store. With the
memory store, queue:restart warns that other processes won’t see the restart. With the
discard store, queue:restart fails. An idle worker sees a restart after its current sleep
or long poll, and a worker that started after the restart ignores it. While a worker can’t
read the cache, it logs a warning, keeps working, and uses the pauses it last read.
queue:pause --all is separate from pauses of single queues. queue:continue --all doesn’t
resume a queue that was paused by name, and queue:continue emails doesn’t resume emails
while every queue is paused. A worker started with --stop-when-empty stops when all of its
queues are paused.
Modules§
- events
- Events that the queue worker dispatches as it processes jobs.
Macros§
- tables
- Define a migration’s
migratefunction to create thedatabasequeue driver’s tables.
Structs§
- Attempt
- One run of a job, with the job’s ID, where the job came from, and how many times it has run.
- Batch
- A snapshot of a batch at the time it was read, with its job counts and the times it was created, cancelled, and finished.
- BatchId
- A batch’s unique ID, which is a time-ordered UUID.
- Callback
List - A batch’s or chain’s callbacks, as a test sees them.
- Connection
Definition - The name and configuration of the connection that a driver’s factory creates a driver for.
- Drivers
- Queue driver factories, configured before the application boots.
- JobId
- A dispatched job’s unique ID, which is a time-ordered UUID.
- JobList
- The jobs waiting in a chain or a batch, as a test sees them.
- JobOptions
- A job’s queue, retries, and timeout, from the options of
#[job(..)]. - JobTimed
Out - The error for a job that ran longer than its
timeoutand was stopped. - Middleware
Group - An ordered list of job middleware, where the first middleware runs first and wraps the rest.
- Missing
Models - The error for a queued job, listener, or callback that can’t run because the rows of some of its models are gone.
- Next
- The rest of a job’s middleware, and its
handle. - Parse
IdError - The error from parsing text that isn’t a UUID as a
JobIdorBatchId. - Pending
Batch - A batch of jobs on its way to the queue.
- Pending
Bulk - Several jobs on their way to the queue together.
- Pending
Chain - A chain of jobs on its way to the queue.
- Pending
Dispatch - A job on its way to the queue.
- Pushed
- A job that a
QueueFakerecorded, decoded as a worker would read it. - Pushed
Batch - A batch that a
QueueFakerecorded, or a batch that’s a step of a chain, with its jobs, name, and options. - Queue
Fake - An active queue fake and its typed assertions.
- Queue
Manager - The application’s queue connections, by name.
- Queue
Sizes - How many jobs a queue holds in each state, as
QueueManager::sizesreports them.
Enums§
- Chain
Dispatched - The first step dispatched by a chain.
- Failed
- What became of a job that failed for good, as
ReservedJob::failreports it. - Reservation
- Whether a job was still a worker’s when the worker renewed, deleted, or released it, as
ReservedJobreports it.
Constants§
- HEARTBEAT
- How often a worker renews the reservation of a job it’s running.
- LEASE
- How long a reservation lasts without being renewed. A job whose worker stopped renewing it is available to other workers once its reservation lapses.
Traits§
- Callback
- A
Queueablestruct withthen,catch, orfinallymethods that a batch or chain calls directly, without queueing them, when it reaches each method’s point. - Catch
- A callback with a
catchmethod. - Chain
Catch - A
catchcallback that doesn’t take a&Batch, so a chain can call it too. - Driver
- A queue backend, which stores a connection’s jobs and hands each one to a worker.
- Finally
- A callback with a
finallymethod, which a batch calls once every one of its jobs has run. - Into
Batch Job - One job of a batch, which is either a job or a chain of jobs.
- Into
Batch Jobs - The jobs of a batch.
- Into
Jobs - One or more jobs to add to a chain, in order.
- Into
Middleware - A type that a job’s
middlewaremethod may return. - Job
- A
Queueablestruct with a handler, which the queue keeps and runs later. - JobResult
- A return type that a job’s
handleandfailedmethods and a callback’s methods support. - JobTypes
- A job type or a tuple of job types that names a chain, such as
TranscribePodcastor(ShipOrder, RecordShipment). - Middleware
- Code that runs around a job’s
handle, such as a check that decides whether the job runs now. - Queueable
- A job, a queued listener’s event, or a callback that the queue can store until a worker runs it.
- Reserved
Job - One reservation of a job, which a worker runs and then settles.
- Then
- A callback with a
thenmethod, which a batch calls once every one of its jobs has succeeded.
Functions§
- batch
- Dispatch jobs as a batch and call its callbacks once they’ve all run.
- bulk
- Push several jobs at once.
- cancel_
batch - Cancel a batch.
- chain
- Chain jobs so that each one runs after the one before it succeeds.
- dispatch
- Dispatch a job to its queue.
- dispatch_
sync - Run a job immediately in this process instead of queueing it.
- fake
- Record this application’s dispatched jobs without pushing or running them.
- find_
batch - Find a batch by its ID, such as to show how far along the batch is.
- manager
- Resolve the application’s queue manager from its context.
Attribute Macros§
- callback
- Make a
Queueablestruct a batch or chainCallback. - job
- Make a
Queueablestruct a queued job. - middleware
- Turn an async function into a job
Middlewarestruct with the function’s name.