pub struct BackgroundTasks { /* private fields */ }Expand description
Background task queue for running tasks after response is sent.
Tasks are executed in the order they are added, after the response has been sent to the client. This is useful for:
- Sending emails
- Writing to external logs
- Triggering webhooks
- Updating caches
§Example
use fastapi_core::extract::BackgroundTasks;
async fn handler(mut tasks: BackgroundTasks) -> &'static str {
tasks.add_task(|| async {
// Send notification email
send_email("user@example.com", "Welcome!").await;
});
"Response sent, email will be sent in background"
}§Note
Background tasks run after the response is sent but before the request context is fully cleaned up. They share the same cancellation context as the request, so long-running tasks should check for cancellation.
Implementations§
Source§impl BackgroundTasks
impl BackgroundTasks
Sourcepub fn add_task<F, Fut>(&mut self, task: F)
pub fn add_task<F, Fut>(&mut self, task: F)
Add a background task.
The task will be executed after the response is sent.
Sourcepub fn add_sync_task<F>(&mut self, task: F)
pub fn add_sync_task<F>(&mut self, task: F)
Add a synchronous background task.
The task will be executed after the response is sent.
Sourcepub fn take_tasks(
&mut self,
) -> Vec<Box<dyn FnOnce() -> Pin<Box<dyn Future<Output = ()> + Send>> + Send>>
pub fn take_tasks( &mut self, ) -> Vec<Box<dyn FnOnce() -> Pin<Box<dyn Future<Output = ()> + Send>> + Send>>
Take all tasks from the queue.
Sourcepub async fn execute_all(self)
pub async fn execute_all(self)
Execute all tasks sequentially.
This is called by the framework after the response is sent. Tasks run in the order they were added (FIFO).
§Error Handling
This method does NOT provide error isolation. If a task panics,
subsequent tasks will not run. For panic isolation, use
Self::execute_with_panic_isolation() instead.
Since tasks run after the response is sent, panics do not affect the HTTP response that was already delivered to the client.
§Example
let response = app.handle(&ctx, &mut request).await;
// Send response to client...
if let Some(tasks) = App::take_background_tasks(&mut request) {
tasks.execute_all().await;
}Sourcepub async fn execute_with_context(self, ctx: &RequestContext)
pub async fn execute_with_context(self, ctx: &RequestContext)
Execute all tasks with cancellation support via RequestContext.
This version checks for cancellation between tasks and respects the request’s cancellation state. Use this when you want background tasks to be cancelled along with the request.
§Arguments
ctx- The request context for cancellation checking
§Cancellation Behavior
- Checks
ctx.is_cancelled()before starting each task - If cancelled, remaining tasks are skipped
- Already-running tasks complete before the check
- Logs the number of skipped tasks
§Integration with asupersync
Background tasks run in the same region as the request. When the region is cancelled (client disconnect, timeout, etc.), subsequent tasks will be skipped. This ensures proper structured concurrency.
§Example
let response = app.handle(&ctx, &mut request).await;
// Send response to client...
if let Some(tasks) = App::take_background_tasks(&mut request) {
tasks.execute_with_context(&ctx).await;
}Sourcepub async fn execute_with_panic_isolation(self)
pub async fn execute_with_panic_isolation(self)
Execute tasks with per-task panic isolation using catch_unwind.
This version catches panics that occur when calling the task closure (i.e., when creating the future), allowing subsequent tasks to continue.
§What Is Caught vs. Not Caught
// CAUGHT: Panic in closure before returning future
tasks.add_task(|| {
panic!("this is caught");
async {} // never reached
});
// NOT CAUGHT: Panic inside async block (during .await)
tasks.add_task(|| async {
panic!("this is NOT caught - propagates and stops remaining tasks");
});Due to Rust’s async limitation, panics inside the async task body
cannot be caught without additional crate dependencies (like futures).
For most use cases where task code is well-behaved, execute_all()
or execute_with_context() is sufficient.
Sourcepub fn into_inner(self) -> BackgroundTasksInner
pub fn into_inner(self) -> BackgroundTasksInner
Get the inner storage for request extensions.
Trait Implementations§
Source§impl Clone for BackgroundTasks
impl Clone for BackgroundTasks
Source§fn clone(&self) -> BackgroundTasks
fn clone(&self) -> BackgroundTasks
1.0.0 · Source§fn clone_from(&mut self, source: &Self)
fn clone_from(&mut self, source: &Self)
source. Read more