Skip to main content

Module background

Module background 

Source
Expand description

Background worker helpers: BackgroundService, delay, CancellationToken. Background work: the BackgroundService worker base class, its host adapter, and cancellation helpers.

§Why

IHostedService is the startup/shutdown hook: start() runs to completion and then the host accepts requests. A worker (queue consumer, outbox publisher, periodic poller) instead runs forever next to the request pipeline. Written as an IHostedService it has to hand-roll the loop, the cancellation flag, the join handle and the shutdown logic. Business code should only write the loop body:

ⓘ
struct OutboxWorker { services: Arc<dyn ScopeFactory> }

#[async_trait]
impl BackgroundService for OutboxWorker {
    async fn execute(&self, ct: CancellationToken) -> Result<()> {
        while !ct.is_cancelled() {
            let scope = self.services.create_scope();
            publish_due(&scope).await?;
            // Interruptible wait: returns `false` immediately on shutdown.
            if !delay(&ct, Duration::from_secs(5)).await {
                break;
            }
        }
        Ok(())
    }
}

Register it with add_background_service_with / add_background_service; the host starts it together with the hosted services and cancels the token on shutdown, so the loop leaves delay at once instead of finishing a long sleep.

§Failure semantics

execute returning Err is a typed failure, not a panic: the adapter logs it when it happens and reports it again from stop(). A panic inside execute is caught by the task and converted to Error::Internal in stop(). A worker that ignores cancellation is aborted after STOP_GRACE so it cannot outlive provider disposal.

Structs§

BackgroundServiceHost
Runs a BackgroundService as an IHostedService.
CancellationToken
A token which can be used to signal a cancellation request to one or more tasks.

Constants§

STOP_GRACE
How long a background worker may take to observe cancellation.

Traits§

BackgroundService
A long-running worker: the host calls execute once on startup and cancels the token on shutdown.
PeriodicBackgroundService
A periodic worker: the framework owns the interval loop, the interruptible wait and stop/join; business code implements tick only.

Functions§

delay
Wait for duration, returning false as soon as ct is cancelled.