Skip to main content

BackgroundService

Trait BackgroundService 

Source
pub trait BackgroundService:
    Send
    + Sync
    + 'static {
    // Required method
    fn execute<'life0, 'async_trait>(
        &'life0 self,
        ct: CancellationToken,
    ) -> Pin<Box<dyn Future<Output = Result<(), Error>> + Send + 'async_trait>>
       where 'life0: 'async_trait,
             Self: 'async_trait;
}
Expand description

A long-running worker: the host calls execute once on startup and cancels the token on shutdown.

Business code only implements the loop body; scope creation, shutdown observation, panic conversion and the join-handle lifecycle belong to the framework (BackgroundServiceHost).

Required Methods§

Source

fn execute<'life0, 'async_trait>( &'life0 self, ct: CancellationToken, ) -> Pin<Box<dyn Future<Output = Result<(), Error>> + Send + 'async_trait>>
where 'life0: 'async_trait, Self: 'async_trait,

Run until ct is cancelled (or the work is finished).

ct is cancelled when the host starts shutting down. Long waits must be interruptible — use delay instead of tokio::time::sleep, so a shutdown does not wait for the next tick.

Dyn Compatibility§

This trait is dyn compatible.

In older versions of Rust, dyn compatibility was called "object safety".

Implementors§