Skip to main content

TaskFn

Struct TaskFn 

Source
pub struct TaskFn<F> { /* private fields */ }
Expand description

Function-backed task implementation.

Wraps a closure F: Fn(CancellationToken) -> Future that creates a fresh future on each spawn call.

§Rules

  • Each spawn() creates an independent future (no implicit shared state).
  • For shared state, pass it explicitly via Arc<...> captured by the closure.
  • Closure has no mutable self (must implement Fn, not FnMut).

Implementations§

Source§

impl<F> TaskFn<F>

Source

pub fn new(name: impl Into<String>, f: F) -> Self

Creates a new function-backed task with the given name.

§Parameters
  • name: Task name (for logging, metrics).
  • f: Closure that creates a future when called.
§Notes

Prefer TaskFn::arc when you need a TaskRef immediately.

Source

pub fn arc(name: impl Into<String>, f: F) -> Arc<Self>

Creates the task and returns it as a shared handle (Arc<dyn Task>).

This is the most common way to create a TaskFn.

§Example
use tokio_util::sync::CancellationToken;
use taskvisor::{TaskFn, TaskRef, TaskError};

let t: TaskRef = TaskFn::arc("hello", |_ctx: CancellationToken| async {
    Ok::<_, TaskError>(())
});
assert_eq!(t.name(), "hello");
Examples found in repository?
examples/control.rs (lines 76-90)
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 74-91)
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 (lines 19-39)
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}

Trait Implementations§

Source§

impl<F: Debug> Debug for TaskFn<F>

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

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

Source§

fn name(&self) -> &str

Returns a stable, human-readable task name. Read more
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. Read more

Auto Trait Implementations§

§

impl<F> Freeze for TaskFn<F>
where F: Freeze,

§

impl<F> RefUnwindSafe for TaskFn<F>
where F: RefUnwindSafe,

§

impl<F> Send for TaskFn<F>
where F: Send,

§

impl<F> Sync for TaskFn<F>
where F: Sync,

§

impl<F> Unpin for TaskFn<F>
where F: Unpin,

§

impl<F> UnsafeUnpin for TaskFn<F>
where F: UnsafeUnpin,

§

impl<F> UnwindSafe for TaskFn<F>
where F: UnwindSafe,

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> 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, 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