pub struct AsyncCron<Z>{ /* 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 implementsTimeZone + 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>
Implementation of the asynchronous cron scheduler.
impl<Z> AsyncCron<Z>
Implementation of the asynchronous cron scheduler.
Sourcepub async fn add_fn<F, T>(&mut self, spec: &str, f: F) -> Result<usize>
pub async fn add_fn<F, T>(&mut self, spec: &str, f: F) -> Result<usize>
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 implementingFuture<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?
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}Sourcepub fn new(tz: Z) -> AsyncCron<Z>
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?
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}Sourcepub async fn remove(&self, id: usize)
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 byadd_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;Sourcepub async fn start_blocking(&mut self)
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:
- Set up communication channels for job management
- Calculate the next execution time for all jobs
- Sleep until the next job is due
- Execute all due jobs as async tasks
- Handle job additions/removals during runtime
- 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(())
}Sourcepub fn set_timezone(&mut self, tz: Z)
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?;Sourcepub async fn start(&mut self)
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?
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}Sourcepub async fn stop(&self)
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?
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}