Skip to main content

Task

Trait Task 

Source
pub trait Task:
    Send
    + Sync
    + 'static {
    // Required methods
    fn name(&self) -> &str;
    fn spawn(&self, ctx: CancellationToken) -> BoxTaskFuture;
}
Expand description

Async, cancelable unit of work managed by a Supervisor.

§Contract

spawn is called once per attempt and must return a fresh, independent future. Implementations must observe ctx.cancelled() and return Err(TaskError::Canceled) promptly. Non-cooperative tasks will be force-terminated after the grace period (GraceExceeded).

Return valueMeaningRestarted?
Ok(())Task completed normallyDepends on RestartPolicy
Err(TaskError::Canceled)Cooperative shutdownNever
Err(TaskError::Fail)Transient failurePer policy, with backoff
Err(TaskError::Timeout)Attempt timed outPer policy, with backoff
Err(TaskError::Fatal)Permanent failureNever

§Cancellation

The CancellationToken ctx is cancelled by the supervisor during shutdown or when the task is removed at runtime.

  • Long-running tasks should poll ctx.cancelled(): tasks that ignore the token will block graceful shutdown until the grace period expires.
  • Short-lived, one-shot tasks that complete quickly may omit this check.

A task that loops forever and only exits via ctx.cancelled() should return Err(TaskError::Canceled); A one-shot task that finishes its work should return Ok(()).

§Also

  • For the closure-based implementation see TaskFn.
  • To configure restart, backoff, and timeout see TaskSpec.

Required Methods§

Source

fn name(&self) -> &str

Task name used in logs, metrics, and shutdown diagnostics.

Source

fn spawn(&self, ctx: CancellationToken) -> BoxTaskFuture

Creates a new future that runs the task until completion or cancellation.

Called once per attempt. Takes &self - each call must return an independent future with no side effects from previous runs.

Implementors§

Source§

impl<Fnc, Fut> Task for TaskFn<Fnc>
where Fnc: Fn(CancellationToken) -> Fut + Send + Sync + 'static, Fut: Future<Output = Result<(), TaskError>> + Send + 'static,