AsyncCron

Struct AsyncCron 

Source
pub struct AsyncCron<Z>
where Z: TimeZone + Send + Sync + 'static, Z::Offset: Send,
{ /* private fields */ }
Expand description

Re-export of the asynchronous cron scheduler.

This is only available when the “async” feature is enabled. Use AsyncCron for asynchronous job scheduling with tokio runtime. An asynchronous cron job scheduler that manages and executes scheduled async jobs.

The AsyncCron struct provides an async-first approach to job scheduling using tokio’s runtime. Jobs are executed as async tasks, allowing for efficient concurrent execution without blocking threads.

§Type Parameters

  • Z - A timezone type that implements TimeZone + Send + Sync + 'static

§Async Runtime

This scheduler requires a tokio runtime to function. All methods are async and jobs are executed as tokio tasks.

§Examples

use chrono::Utc;
use cron_tab::AsyncCron;

let mut cron = AsyncCron::new(Utc);
 
let job_id = cron.add_fn("*/5 * * * * * *", || async {
    println!("This async job runs every 5 seconds");
    // Can perform async operations here
    tokio::time::sleep(tokio::time::Duration::from_millis(100)).await;
}).await?;

cron.start().await;
// Jobs will now execute according to their schedule
 
// Later, you can stop the scheduler
cron.stop().await;

Implementations§

Source§

impl<Z> AsyncCron<Z>
where Z: TimeZone + Send + Sync + 'static, Z::Offset: Send,

Implementation of the asynchronous cron scheduler.

Source

pub async fn add_fn<F, T>(&mut self, spec: &str, f: F) -> Result<usize>
where F: 'static + Fn() -> T + Send + Sync, T: 'static + Future<Output = ()> + Send,

Adds an async function to be executed according to the specified cron schedule.

The function should return a Future that will be awaited when the job executes. This allows for true asynchronous job execution without blocking threads.

§Arguments
  • spec - A cron expression string in the format “sec min hour day month weekday year”
  • f - A function that returns a Future implementing Future<Output = ()> + Send + 'static
§Returns

Returns a Result<usize, CronError> where the usize is a unique job ID that can be used with remove to cancel the job.

§Errors

Returns CronError::ParseError if the cron expression is invalid.

§Examples
use chrono::Utc;
use cron_tab::AsyncCron;
use std::sync::Arc;
use tokio::sync::Mutex;

let mut cron = AsyncCron::new(Utc);

// Simple async job
let job_id = cron.add_fn("*/10 * * * * * *", || async {
    println!("Async job executed!");
    tokio::time::sleep(tokio::time::Duration::from_millis(100)).await;
}).await?;

// Job with shared state
let counter = Arc::new(Mutex::new(0));
let counter_clone = counter.clone();
cron.add_fn("* * * * * * *", move || {
    let counter = counter_clone.clone();
    async move {
        let mut count = counter.lock().await;
        *count += 1;
        println!("Count: {}", *count);
    }
}).await?;
Examples found in repository?
examples/async_simple.rs (lines 15-23)
8async fn main() {
9    let local_tz = Local::from_offset(&FixedOffset::east_opt(7).unwrap());
10    let mut cron = AsyncCron::new(local_tz);
11
12    cron.start().await;
13
14    let counter = Arc::new(Mutex::new(1));
15    cron.add_fn("* * * * * *", move || {
16        let counter = counter.clone();
17        async move {
18            let mut counter = counter.lock().await;
19            *counter += 1;
20            let now = Local::now().to_string();
21            println!("{} counter value: {}", now, counter);
22        }
23    })
24    .await
25    .unwrap();
26
27    std::thread::sleep(std::time::Duration::from_secs(10));
28
29    // stop cron
30    cron.stop().await;
31}
Source

pub fn new(tz: Z) -> AsyncCron<Z>

Creates a new async cron scheduler with the specified timezone.

The scheduler is created in a stopped state. Call start to begin executing scheduled jobs.

§Arguments
  • tz - The timezone to use for all scheduling calculations
§Examples
use chrono::{Utc, FixedOffset};
use cron_tab::AsyncCron;

// UTC timezone
let cron_utc = AsyncCron::new(Utc);

// Fixed offset timezone (Tokyo: UTC+9)
let tokyo_tz = FixedOffset::east_opt(9 * 3600).unwrap();
let cron_tokyo = AsyncCron::new(tokyo_tz);
Examples found in repository?
examples/async_simple.rs (line 10)
8async fn main() {
9    let local_tz = Local::from_offset(&FixedOffset::east_opt(7).unwrap());
10    let mut cron = AsyncCron::new(local_tz);
11
12    cron.start().await;
13
14    let counter = Arc::new(Mutex::new(1));
15    cron.add_fn("* * * * * *", move || {
16        let counter = counter.clone();
17        async move {
18            let mut counter = counter.lock().await;
19            *counter += 1;
20            let now = Local::now().to_string();
21            println!("{} counter value: {}", now, counter);
22        }
23    })
24    .await
25    .unwrap();
26
27    std::thread::sleep(std::time::Duration::from_secs(10));
28
29    // stop cron
30    cron.stop().await;
31}
Source

pub async fn remove(&self, id: usize)

Removes a job from the scheduler.

Once removed, the job will no longer be executed. If the job ID doesn’t exist, this method does nothing. If the scheduler is running, the removal is handled asynchronously via the scheduler’s event loop.

§Arguments
  • id - The job ID returned by add_fn
§Examples
use chrono::Utc;
use cron_tab::AsyncCron;

let mut cron = AsyncCron::new(Utc);
let job_id = cron.add_fn("* * * * * * *", || async {
    println!("This will be removed");
}).await?;

cron.start().await;
 
// Later, remove the job
cron.remove(job_id).await;
Source

pub async fn start_blocking(&mut self)

Runs the scheduler in the current task (blocking).

This method runs the main scheduler loop in the current async context, blocking until stop is called. This is useful when you want to run the scheduler as the main task of your application.

§Behavior

The scheduler will:

  1. Set up communication channels for job management
  2. Calculate the next execution time for all jobs
  3. Sleep until the next job is due
  4. Execute all due jobs as async tasks
  5. Handle job additions/removals during runtime
  6. Repeat until stopped
§Examples
use chrono::Utc;
use cron_tab::AsyncCron;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let mut cron = AsyncCron::new(Utc);
    cron.add_fn("0 0 * * * * *", || async {
        println!("Top of the hour!");
    }).await?;

    // This will block until stop() is called from another task
    cron.start_blocking().await;
    Ok(())
}
Source

pub fn set_timezone(&mut self, tz: Z)

Sets the timezone for the scheduler.

This affects how cron expressions are interpreted for all future job executions. Existing jobs will use the new timezone for their next scheduled execution.

§Arguments
  • tz - The new timezone to use
§Examples
use chrono::{Utc, FixedOffset};
use cron_tab::AsyncCron;

// Create async cron with UTC timezone
let mut cron_utc = AsyncCron::new(Utc);

// Create a separate async cron with Tokyo timezone  
let tokyo_tz = FixedOffset::east_opt(9 * 3600).unwrap();
let mut cron_tokyo = AsyncCron::new(tokyo_tz);

// Each scheduler uses its own timezone for job scheduling
cron_utc.add_fn("0 0 12 * * * *", || async {
    println!("Noon UTC");
}).await?;

cron_tokyo.add_fn("0 0 12 * * * *", || async {
    println!("Noon Tokyo time");
}).await?;
Source

pub async fn start(&mut self)

Starts the cron scheduler in a background task.

This method spawns a new tokio task that will continuously monitor for jobs that need to be executed and spawn additional tasks to run them. The method returns immediately, allowing your program to continue.

§Async Runtime

The scheduler runs as a tokio task and spawns additional tasks for each job execution. This ensures that long-running async jobs don’t block the scheduler or other jobs.

§Examples
use chrono::Utc;
use cron_tab::AsyncCron;

let mut cron = AsyncCron::new(Utc);
cron.add_fn("*/2 * * * * * *", || async {
    println!("Job executed every 2 seconds");
    // Can perform async operations here
    tokio::time::sleep(tokio::time::Duration::from_millis(500)).await;
}).await?;

// Start the scheduler
cron.start().await;

// The current task can continue with other work
tokio::time::sleep(tokio::time::Duration::from_secs(10)).await;

// Stop the scheduler
cron.stop().await;
Examples found in repository?
examples/async_simple.rs (line 12)
8async fn main() {
9    let local_tz = Local::from_offset(&FixedOffset::east_opt(7).unwrap());
10    let mut cron = AsyncCron::new(local_tz);
11
12    cron.start().await;
13
14    let counter = Arc::new(Mutex::new(1));
15    cron.add_fn("* * * * * *", move || {
16        let counter = counter.clone();
17        async move {
18            let mut counter = counter.lock().await;
19            *counter += 1;
20            let now = Local::now().to_string();
21            println!("{} counter value: {}", now, counter);
22        }
23    })
24    .await
25    .unwrap();
26
27    std::thread::sleep(std::time::Duration::from_secs(10));
28
29    // stop cron
30    cron.stop().await;
31}
Source

pub async fn stop(&self)

Stops the cron scheduler.

This sends a stop signal to the scheduler task, causing it to exit gracefully. Any currently executing async jobs will continue to completion, but no new jobs will be started.

§Examples
use chrono::Utc;
use cron_tab::AsyncCron;

let mut cron = AsyncCron::new(Utc);
cron.add_fn("* * * * * * *", || async {
    println!("Hello async world!");
}).await?;
cron.start().await;

// Later, stop the scheduler
cron.stop().await;
Examples found in repository?
examples/async_simple.rs (line 30)
8async fn main() {
9    let local_tz = Local::from_offset(&FixedOffset::east_opt(7).unwrap());
10    let mut cron = AsyncCron::new(local_tz);
11
12    cron.start().await;
13
14    let counter = Arc::new(Mutex::new(1));
15    cron.add_fn("* * * * * *", move || {
16        let counter = counter.clone();
17        async move {
18            let mut counter = counter.lock().await;
19            *counter += 1;
20            let now = Local::now().to_string();
21            println!("{} counter value: {}", now, counter);
22        }
23    })
24    .await
25    .unwrap();
26
27    std::thread::sleep(std::time::Duration::from_secs(10));
28
29    // stop cron
30    cron.stop().await;
31}

Trait Implementations§

Source§

impl<Z> Clone for AsyncCron<Z>
where Z: TimeZone + Send + Sync + 'static + Clone, Z::Offset: Send,

Source§

fn clone(&self) -> AsyncCron<Z>

Returns a duplicate 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<Z> Debug for AsyncCron<Z>
where Z: TimeZone + Send + Sync + 'static + Debug, Z::Offset: Send,

Source§

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

Formats the value using the given formatter. Read more

Auto Trait Implementations§

§

impl<Z> Freeze for AsyncCron<Z>
where Z: Freeze,

§

impl<Z> !RefUnwindSafe for AsyncCron<Z>

§

impl<Z> Send for AsyncCron<Z>

§

impl<Z> Sync for AsyncCron<Z>

§

impl<Z> Unpin for AsyncCron<Z>
where Z: Unpin,

§

impl<Z> !UnwindSafe for AsyncCron<Z>

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> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. 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> ToOwned for T
where T: Clone,

Source§

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

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.