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, notFnMut).
Implementations§
Source§impl<F> TaskFn<F>
impl<F> TaskFn<F>
Sourcepub fn new(name: impl Into<String>, f: F) -> Self
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.
Sourcepub fn arc(name: impl Into<String>, f: F) -> Arc<Self>
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
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§
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> 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