pub struct TaskSpec { /* private fields */ }Expand description
Specification for running a task under supervision.
Bundles together:
- The task itself (
TaskRef) - Restart policy (
RestartPolicy) - Backoff policy (
BackoffPolicy) - Optional execution timeout
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
impl TaskSpec
Sourcepub fn new(
task: TaskRef,
restart: RestartPolicy,
backoff: BackoffPolicy,
timeout: Option<Duration>,
) -> Self
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 executerestart: When to restart (never/always/on-failure)backoff: How to delay between retriestimeout: 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
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}Sourcepub fn with_defaults(task: TaskRef, cfg: &SupervisorConfig) -> Self
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 executecfg: Config to inherit restart/backoff/timeout from
Sourcepub fn restart(&self) -> RestartPolicy
pub fn restart(&self) -> RestartPolicy
Returns the restart policy.
Sourcepub fn backoff(&self) -> BackoffPolicy
pub fn backoff(&self) -> BackoffPolicy
Returns the backoff policy.
Sourcepub fn with_timeout(self, timeout: Option<Duration>) -> Self
pub fn with_timeout(self, timeout: Option<Duration>) -> Self
Returns a new spec with updated timeout.
Sourcepub fn with_backoff(self, backoff: BackoffPolicy) -> Self
pub fn with_backoff(self, backoff: BackoffPolicy) -> Self
Returns a new spec with updated backoff.
Sourcepub fn with_restart(self, restart: RestartPolicy) -> Self
pub fn with_restart(self, restart: RestartPolicy) -> Self
Returns a new spec with updated restart policy.
Trait Implementations§
Auto Trait Implementations§
impl Freeze for TaskSpec
impl !RefUnwindSafe for TaskSpec
impl Send for TaskSpec
impl Sync for TaskSpec
impl Unpin for TaskSpec
impl UnsafeUnpin for TaskSpec
impl !UnwindSafe for TaskSpec
Blanket Implementations§
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Mutably borrows from an owned value. Read more