Skip to main content

IHostedService

Trait IHostedService 

Source
pub trait IHostedService: Send + Sync {
    // Required method
    fn start<'life0, 'async_trait>(
        &'life0 self,
    ) -> Pin<Box<dyn Future<Output = Result<()>> + Send + 'async_trait>>
       where Self: 'async_trait,
             'life0: 'async_trait;

    // Provided method
    fn stop<'life0, 'async_trait>(
        &'life0 self,
    ) -> Pin<Box<dyn Future<Output = Result<()>> + Send + 'async_trait>>
       where Self: 'async_trait,
             'life0: 'async_trait { ... }
}
Expand description

Background service that is started when the host starts and stopped when the host performs a graceful shutdown.

Analogous to ASP.NET Core’s IHostedService.

Use this for:

  • Data initialization / seeding at application startup
  • Background polling loops
  • Queue consumers
  • Connection pool warmup

§Example

#[derive(Default)]
struct DbInitService;

#[async_trait]
impl IHostedService for DbInitService {
    async fn start(&self) -> Result<()> {
        tracing::info!("[DbInitService] Running migrations...");
        run_migrations().await?;
        tracing::info!("[DbInitService] Seeding data...");
        seed_data().await?;
        Ok(())
    }

    async fn stop(&self) -> Result<()> {
        tracing::info!("[DbInitService] Shutting down...");
        Ok(())
    }
}

Required Methods§

Source

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

Called when the host starts.

The host waits for all hosted services to finish start() before beginning to accept incoming requests.

Provided Methods§

Source

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

Called during a graceful shutdown.

The host calls stop() on all hosted services concurrently after the HTTP server has stopped accepting new connections.

Dyn Compatibility§

This trait is dyn compatible.

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

Implementors§