Skip to main content

daemon

Attribute Macro daemon 

Source
#[daemon]
Expand description

Marks a function as a long-running daemon.

Daemons are singleton background tasks that run continuously. They support leader election (only one instance runs across the cluster), automatic restart on panic, and graceful shutdown handling.

§Attributes

  • leader_elected = true - Only one instance runs across cluster (default: true)
  • restart_on_panic = true - Restart if daemon panics (default: true)
  • restart_delay = "5s" - Delay before restart after failure
  • startup_delay = "10s" - Delay before first execution after startup
  • max_restarts = 10 - Maximum restart attempts (default: unlimited)

§Shutdown Handling

Daemons must handle graceful shutdown by checking ctx.shutdown_signal():

loop {
    // Do work
    tokio::select! {
        _ = tokio::time::sleep(Duration::from_secs(60)) => {}
        _ = ctx.shutdown_signal() => break,
    }
}

§Example

#[forge::daemon(startup_delay = "5s", restart_on_panic = true)]
pub async fn heartbeat_daemon(ctx: &DaemonContext) -> Result<()> {
    loop {
        // Update heartbeat
        sqlx::query("UPDATE app_status SET heartbeat = NOW()").execute(ctx.db()).await?;

        tokio::select! {
            _ = tokio::time::sleep(Duration::from_secs(30)) => {}
            _ = ctx.shutdown_signal() => break,
        }
    }
    Ok(())
}

#[forge::daemon(leader_elected = false, max_restarts = 5)]
pub async fn worker_daemon(ctx: &DaemonContext) -> Result<()> {
    // Runs on all nodes, limited restarts
}