Skip to main content

TaskSpec

Struct TaskSpec 

Source
pub struct TaskSpec { /* private fields */ }
Expand description

Specification for running a task under supervision.

Bundles together:

It can be created manually with TaskSpec::new or derived from a global SupervisorConfig via TaskSpec::with_defaults.

§Example

use tokio_util::sync::CancellationToken;
use taskvisor::{TaskSpec, TaskFn, SupervisorConfig, RestartPolicy, BackoffPolicy, TaskRef, TaskError};
use std::time::Duration;

let demo: TaskRef = TaskFn::arc("demo", |_ctx: CancellationToken| async move {
    Ok::<(), TaskError>(())
});

// Explicit configuration:
let spec = TaskSpec::new(
    demo.clone(),
    RestartPolicy::Never,
    BackoffPolicy::default(),
    None,
);
assert!(spec.timeout().is_none());

// Inherit from global config:
let cfg = SupervisorConfig::default();
let spec2 = TaskSpec::with_defaults(demo, &cfg);
// `cfg.timeout = 0s` is treated as `None`

Implementations§

Source§

impl TaskSpec

Source

pub fn new( task: TaskRef, restart: RestartPolicy, backoff: BackoffPolicy, timeout: Option<Duration>, ) -> Self

Creates a new task specification with explicit parameters.

§Parameters
  • task: Task to execute
  • restart: When to restart (never/always/on-failure)
  • backoff: How to delay between retries
  • timeout: Optional per-attempt timeout (None = no timeout)
Examples found in repository?
examples/control.rs (lines 91-96)
74fn make_worker(name: &'static str) -> taskvisor::TaskSpec {
75    let task: taskvisor::TaskRef =
76        taskvisor::TaskFn::arc(name, move |ctx: CancellationToken| async move {
77            println!("{:>4}[{name}] started", "");
78
79            let mut counter = 0u32;
80            loop {
81                if ctx.is_cancelled() {
82                    println!("{:>4}[{name}] cancelled", "");
83                    return Err(taskvisor::TaskError::Canceled);
84                }
85
86                counter += 1;
87                println!("{:>4}[{name}] tick #{counter}", "");
88                tokio::time::sleep(Duration::from_millis(500)).await;
89            }
90        });
91    taskvisor::TaskSpec::new(
92        task,
93        taskvisor::RestartPolicy::default(),
94        taskvisor::BackoffPolicy::default(),
95        None,
96    )
97}
More examples
Hide additional examples
examples/subscriber.rs (lines 92-97)
70fn make_spec() -> taskvisor::TaskSpec {
71    let counter = Arc::new(AtomicU32::new(0));
72
73    let task: taskvisor::TaskRef =
74        taskvisor::TaskFn::arc("flaky", move |ctx: CancellationToken| {
75            let counter = Arc::clone(&counter);
76            async move {
77                if ctx.is_cancelled() {
78                    return Err(taskvisor::TaskError::Canceled);
79                }
80
81                let attempt = counter.fetch_add(1, Ordering::Relaxed) + 1;
82                sleep(Duration::from_millis(100)).await;
83
84                if attempt <= 4 {
85                    return Err(taskvisor::TaskError::Fail {
86                        reason: format!("attempt {attempt} failed"),
87                    });
88                }
89                Ok(())
90            }
91        });
92    taskvisor::TaskSpec::new(
93        task,
94        taskvisor::RestartPolicy::OnFailure,
95        taskvisor::BackoffPolicy::default(),
96        None,
97    )
98}
examples/controller.rs (line 42)
18fn make_spec(name: &'static str, duration_ms: u64) -> taskvisor::TaskSpec {
19    let task: taskvisor::TaskRef = taskvisor::TaskFn::arc(
20        name,
21        move |ctx: tokio_util::sync::CancellationToken| async move {
22            println!("{:>6}[{name}] started", "");
23
24            let start = tokio::time::Instant::now();
25            let sleep = tokio::time::sleep(Duration::from_millis(duration_ms));
26
27            tokio::pin!(sleep);
28            tokio::select! {
29                _ = &mut sleep => {
30                    println!("{:>6}[{name}] completed in {:?}", "", start.elapsed());
31                    Ok(())
32                }
33                _ = ctx.cancelled() => {
34                    println!("{:>6}[{name}] cancelled after {:?}", "", start.elapsed());
35                    Err(taskvisor::TaskError::Canceled)
36                }
37            }
38        },
39    );
40    let policy = taskvisor::RestartPolicy::Never;
41    let backoff = taskvisor::BackoffPolicy::default();
42    taskvisor::TaskSpec::new(task, policy, backoff, None)
43}
Source

pub fn with_defaults(task: TaskRef, cfg: &SupervisorConfig) -> Self

Creates a task specification inheriting defaults from global config.

Uses SupervisorConfig::default_timeout() so that 0s in config is treated as None.

§Parameters
  • task: Task to execute
  • cfg: Config to inherit restart/backoff/timeout from
Source

pub fn task(&self) -> &TaskRef

Returns reference to the task.

Source

pub fn name(&self) -> &str

Convenience: returns the task name.

Source

pub fn restart(&self) -> RestartPolicy

Returns the restart policy.

Source

pub fn backoff(&self) -> BackoffPolicy

Returns the backoff policy.

Source

pub fn timeout(&self) -> Option<Duration>

Returns the timeout, if configured.

Source

pub fn with_timeout(self, timeout: Option<Duration>) -> Self

Returns a new spec with updated timeout.

Source

pub fn with_backoff(self, backoff: BackoffPolicy) -> Self

Returns a new spec with updated backoff.

Source

pub fn with_restart(self, restart: RestartPolicy) -> Self

Returns a new spec with updated restart policy.

Trait Implementations§

Source§

impl Clone for TaskSpec

Source§

fn clone(&self) -> TaskSpec

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V