Skip to main content

SupervisedTask

Trait SupervisedTask 

Source
pub trait SupervisedTask:
    Clone
    + Send
    + 'static {
    // Required method
    fn run(
        self,
        cancel: CancellationToken,
    ) -> impl Future<Output = TaskResult> + Send;
}
Expand description

A long-lived unit of work managed by the supervisor.

Every start or restart clones the registered instance and passes the clone to run. Owned fields reset on every run; Arc fields are shared.

run outcomeSupervisor reaction
Ok(())Completed; not restarted
Err(_) or panicRestarted with backoff, Dead once the restart limit is reached

cancel fires on kill, restart and shutdown. The run then has stop_timeout to return before its future is dropped. Ignore it, wrap the work in cancel.run_until_cancelled(..), or select! on cancel.cancelled() when there is cleanup to do.

§Example

use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::time::Duration;
use task_supervisor::{CancellationToken, SupervisedTask, TaskResult};

#[derive(Clone)]
struct Worker {
    /// Reset on every run (owned, cloned from the original).
    polls: u64,
    /// Shared across runs (`Arc`, cloned by reference).
    total_polls: Arc<AtomicUsize>,
    db: Arc<Db>,
}

impl SupervisedTask for Worker {
    async fn run(mut self, cancel: CancellationToken) -> TaskResult {
        loop {
            tokio::select! {
                _ = cancel.cancelled() => break,
                _ = tokio::time::sleep(Duration::from_secs(1)) => {
                    self.polls += 1;
                    self.total_polls.fetch_add(1, Ordering::Relaxed);
                }
            }
        }
        self.db.flush().await?; // cleanup after cancellation
        Ok(())
    }
}

Required Methods§

Source

fn run( self, cancel: CancellationToken, ) -> impl Future<Output = TaskResult> + Send

Runs one instance of the task until it completes, fails, or is cancelled.

Dyn Compatibility§

This trait is not dyn compatible.

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

Implementors§