Struct workflow_task::Task
source · pub struct Task<A, T>where
A: Send,
T: 'static,{ /* private fields */ }
Expand description
Task
{self::Task} struct allows you to spawn an async fn that can run
in a loop as a task (similar to a thread), checking for a
termination signal (so that execution can be aborted),
upon completion returning a value to the creator.
You can pass a channel
as an argument to the async
function if you wish to communicate with the task.
NOTE: You should always call task.join().await
to await
for the task completion if re-using the task.
use workflow_task::{task, TaskResult};
let task = task!(
|args : (), stop : Receiver<()>| async move {
let mut index = args;
loop {
if stop.try_recv().is_ok() {
break;
}
// ... do something ...
index += 1;
}
return index;
}
);
// spawn the task instance ...
// passing 256 as the `args` argument
task.run(256)?;
// signal termination ...
task.stop()?;
// await for the task completion ...
// the `result` is the returned `index` value
let result = task.join().await?;
// rinse and repeat if needed
task.run(256)?;
Implementations§
source§impl<A, T> Task<A, T>where
A: Send + Sync + 'static,
T: Send + 'static,
impl<A, T> Task<A, T>where
A: Send + Sync + 'static,
T: Send + 'static,
sourcepub fn new<FN>(task_fn: FN) -> Task<A, T>where
FN: Send + Sync + Fn(A, Receiver<()>) -> FnReturn<T> + 'static,
pub fn new<FN>(task_fn: FN) -> Task<A, T>where
FN: Send + Sync + Fn(A, Receiver<()>) -> FnReturn<T> + 'static,
Create a new Task
instance by supplying it with
an async closure that has 2 arguments:
use workflow_task::task;
task!(|args:bool, signal| async move {
// ...
return true;
});
sourcepub fn blank() -> Self
pub fn blank() -> Self
Create an instance of the task without any task function.
The task function can be passed later via Task::set_task_fn()
.
sourcepub fn set_task_fn<FN>(&self, task_fn: FN)where
FN: Send + Sync + Fn(A, Receiver<()>) -> FnReturn<T> + 'static,
pub fn set_task_fn<FN>(&self, task_fn: FN)where
FN: Send + Sync + Fn(A, Receiver<()>) -> FnReturn<T> + 'static,
Replace task fn with an alternate function. The task must be restarted for the replacement to take effect. The function passed does not need to be boxed.
sourcepub fn run(&self, args: A) -> TaskResult<&Self>
pub fn run(&self, args: A) -> TaskResult<&Self>
Run the task supplying the provided argument to the closure supplied at creation.
sourcepub fn stop(&self) -> TaskResult<()>
pub fn stop(&self) -> TaskResult<()>
Signal termination on the channel supplied to the task closure; The task has to check for the signal periodically or await on the future of the signal.
sourcepub async fn join(&self) -> TaskResult<T>
pub async fn join(&self) -> TaskResult<T>
Blocks until the task exits. Resolves immediately if the task is not running.
sourcepub async fn stop_and_join(&self) -> TaskResult<T>
pub async fn stop_and_join(&self) -> TaskResult<T>
Signals termination and blocks until the task exits.