Task

Trait Task 

Source
pub trait Task:
    Send
    + Sync
    + 'static {
    // Required methods
    fn name(&self) -> &str;
    fn spawn(
        &self,
        ctx: CancellationToken,
    ) -> Pin<Box<dyn Future<Output = Result<(), TaskError>> + Send + 'static>>;
}
Expand description

Asynchronous, cancelable unit of work.

A Task represents a unit of work that can be:

§Requirements

  • Cancellation: implementations must observe ctx.cancelled() at safe await points and return Err(TaskError::Canceled) promptly on shutdown.

§Example

use std::{future::Future, pin::Pin, time::Duration};
use tokio_util::sync::CancellationToken;
use taskvisor::{Task, TaskError};

struct MyTask;

impl Task for MyTask {
    fn name(&self) -> &str { "my-task" }

    fn spawn(&self, ctx: CancellationToken)
        -> Pin<Box<dyn Future<Output = Result<(), TaskError>> + Send + 'static>>
    {
        Box::pin(async move {
            loop {
                // Do one unit of work (replace with real IO/compute)
                // Safe point with cancellation via select
                tokio::select! {
                    _ = ctx.cancelled() => {
                        return Err(TaskError::Canceled);
                    }
                    _ = tokio::time::sleep(Duration::from_millis(200)) => {
                        // work chunk finished; continue loop
                    }
                }
            }
        })
    }
}

Required Methods§

Source

fn name(&self) -> &str

Returns a stable, human-readable task name.

Used for logging, metrics, and stuck task detection during shutdown.

Source

fn spawn( &self, ctx: CancellationToken, ) -> Pin<Box<dyn Future<Output = Result<(), TaskError>> + Send + 'static>>

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

§Cancellation requirements

Implementations must observe ctx.cancelled() at safe await points and return Err(TaskError::Canceled) promptly upon shutdown.

§Stateless execution

This method takes &self (not &mut self), meaning:

  • Safe to call from multiple actors concurrently
  • Each call returns an independent future
  • No shared mutable state between spawns

Implementors§

Source§

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