Struct sacs::task::Task

source ·
pub struct Task { /* private fields */ }
Expand description

Task represents single job with it’s schedule, attributes and state.

Implementations§

source§

impl Task

source

pub fn new<T>(schedule: TaskSchedule, job: T) -> Self
where T: 'static + FnMut(JobId) -> Pin<Box<dyn Future<Output = ()> + Send>> + Send + Sync,

Creates new Task with specified schedule, job function and default TaskId.

§Examples
use sacs::task::{CronOpts, Task, TaskSchedule};
use std::time::Duration;

let schedule = TaskSchedule::Cron("*/5 * * * * *".try_into().unwrap(), CronOpts::default());
let task = Task::new(schedule, |id| {
    Box::pin(async move {
        // Actual async workload here
        tokio::time::sleep(Duration::from_secs(1)).await;
        // ...
        println!("Job {id} finished.");
        })
    });
source

pub fn with_id(self, id: impl Into<TaskId>) -> Self

Set explicit TaskId to the existing Task.

This method is useful if you need to know TaskId before task was scheduled.

§Note:

If you provide explicit TaskId value, your responsibility is to ensure uniqueness of the TaskId within instance of Scheduler.

This method consumes Task instance and returns the same instance with specified Id. Since Task is cloneable this method can be used to create several identical tasks with different TaskIds.

§Examples:
use sacs::task::{CronOpts, Task, TaskId, TaskSchedule};
use std::time::Duration;
use uuid::Uuid;

let schedule = TaskSchedule::Cron("*/5 * * * * *".try_into().unwrap(), CronOpts::default());
let task1_id = Uuid::new_v4();
let task_id = task1_id.clone();

let task1 = Task::new(schedule.clone(), move |id| {
    let task_id = task_id.clone();
    Box::pin(async move {
        println!("TaskId={task_id}.");
        // Actual async workload here
        tokio::time::sleep(Duration::from_secs(1)).await;
        // ...
        println!("Job {id} finished.");
        })
    }).with_id(task1_id);

let task2 = task1.clone().with_id(Uuid::new_v4());

let task3 = Task::new(schedule, |id| {
    Box::pin(async move {
        // Actual async workload here
        tokio::time::sleep(Duration::from_secs(1)).await;
        // ...
        println!("Job {id} finished.");
        })
    }).with_id("This is abstract unique task id");
source

pub fn with_schedule(self, schedule: impl Into<TaskSchedule>) -> Self

Set specific TaskSchedule to the existing Task.

Method is useful if you need to create new task based on existing (not scheduled yet) Task.

Method consumes Task instance and returns the same instance with specified TaskSchedule. Since Task is cloneable this method can be used to create several identical tasks with different schedules.

Be careful: Task::clone() doesn’t change TaskId, so it’s your responsibility to ensure uniqueness of task’s Id before posting it to Scheduler. Anyway Scheduler::add() method rejects new Task if the same (with the same TaskId) is already present, even if it’s finished but not removed by getting it’s status or by garbage collector.

§Examples:
use sacs::task::{Task, TaskSchedule};
use std::time::Duration;

let task1 = Task::new(TaskSchedule::Once, move |id| {
    Box::pin(async move {
        println!("Starting job {id}.");
        // Actual async workload here
        tokio::time::sleep(Duration::from_secs(1)).await;
        // ...
        println!("Job {id} finished.");
        })
    });

let task2 = task1.clone()
        .with_schedule(TaskSchedule::OnceDelayed(Duration::from_secs(5)))
        .with_id("Execute once with 5s delay");

let task3 = task1.clone()
        .with_schedule(TaskSchedule::IntervalDelayed(
            Duration::from_secs(2),
            Duration::from_secs(1),
        ))
        .with_id("Repeats every 2s");
source

pub fn new_with_id<T>(schedule: TaskSchedule, job: T, id: TaskId) -> Self
where T: 'static + FnMut(JobId) -> Pin<Box<dyn Future<Output = ()> + Send>> + Send + Sync,

👎Deprecated since 0.4.2: please use with_id method instead.

Create a new Task with a specified schedule, job function and explicit TaskId.

This method is useful if you need to know TaskId before task was scheduled. Or need to use TaskId within job context: for particular task it’s TaskId is constant value, but JobId varies for each task run.

§Note:

If you provide explicit TaskId value, your responsibility is to ensure uniqueness of the TaskId within instance of Scheduler.

§Examples:
use sacs::task::{CronOpts, Task, TaskId, TaskSchedule};
use std::time::Duration;
use uuid::Uuid;

let schedule = TaskSchedule::Cron("*/5 * * * * *".try_into().unwrap(), CronOpts::default());
let task1_id = Uuid::new_v4();
let task_id = task1_id.clone();

let task1 = Task::new_with_id(schedule.clone(), move |id| {
    let task_id = task_id.clone();
    Box::pin(async move {
        println!("TaskId={task_id}.");
        // Actual async workload here
        tokio::time::sleep(Duration::from_secs(1)).await;
        // ...
        println!("Job {id} finished.");
        })
    }, task1_id.into());

let task2 = Task::new_with_id(schedule, |id| {
    Box::pin(async move {
        // Actual async workload here
        tokio::time::sleep(Duration::from_secs(1)).await;
        // ...
        println!("Job {id} finished.");
        })
    }, Uuid::new_v4().into());
source

pub fn id(&self) -> TaskId

Returns task’s TaskId, it can be used to drop task or to get it’s status.

source

pub fn schedule(&self) -> TaskSchedule

Returns TaskSchedule associated with the task.

source

pub fn status(&self) -> TaskStatus

Returns task’s status.

Trait Implementations§

source§

impl Clone for Task

source§

fn clone(&self) -> Task

Returns a copy of the value. Read more
1.0.0 · source§

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

Performs copy-assignment from source. Read more
source§

impl Debug for Task

source§

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

Formats the value using the given formatter. Read more

Auto Trait Implementations§

§

impl Freeze for Task

§

impl !RefUnwindSafe for Task

§

impl Send for Task

§

impl Sync for Task

§

impl Unpin for Task

§

impl !UnwindSafe for Task

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> Instrument for T

source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
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,

§

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

§

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

§

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

source§

impl<T> WithSubscriber for T

source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more