Skip to main content

Cron

Struct Cron 

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

Re-export of the synchronous cron scheduler.

This is only available when the “sync” feature is enabled. Use Cron for synchronous job scheduling with threads. A synchronous cron job scheduler that manages and executes scheduled jobs.

The Cron struct provides a thread-safe way to schedule jobs using cron expressions. Jobs are executed in separate threads as they become due, allowing for concurrent execution without blocking the scheduler.

§Type Parameters

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

§Thread Safety

This struct is thread-safe and can be safely shared between threads. All jobs are executed in separate threads, and the scheduler itself runs in a background thread.

§Examples

use chrono::Utc;
use cron_tab::Cron;

let mut cron = Cron::new(Utc);
let job_id = cron.add_fn("*/5 * * * * * *", || {
    println!("This job runs every 5 seconds");
}).unwrap();

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

Implementations§

Source§

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

Implementation of the synchronous cron scheduler.

Source

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

Creates a new 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::Cron;

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

// Fixed offset timezone (Tokyo: UTC+9)
let tokyo_tz = FixedOffset::east_opt(9 * 3600).unwrap();
let cron_tokyo = Cron::new(tokyo_tz);
Examples found in repository?
examples/simple.rs (line 6)
4fn main() {
5    let local_tz = Local::from_offset(&FixedOffset::east_opt(7).unwrap());
6    let mut cron = cron_tab::Cron::new(local_tz);
7
8    let first_job_id = cron.add_fn("* * * * * * *", print_now).unwrap();
9
10    // start cron in background
11    cron.start();
12
13    cron.add_fn("* * * * * *", move || {
14        println!("add_fn {}", Local::now().to_string());
15    })
16    .unwrap();
17
18    // remove job_test
19    cron.remove(first_job_id);
20
21    std::thread::sleep(std::time::Duration::from_secs(10));
22
23    // stop cron
24    cron.stop();
25}
More examples
Hide additional examples
examples/one_time_execution.rs (line 13)
10fn main() {
11    println!("=== One-Time Task Execution Example ===\n");
12
13    let mut cron = Cron::new(Utc);
14
15    // Shared counter to track execution
16    let counter = Arc::new(Mutex::new(0));
17
18    // Example 1: Execute once after a delay
19    println!("Scheduling job to execute after 2 seconds...");
20    let counter1 = Arc::clone(&counter);
21    cron.add_fn_after(std::time::Duration::from_secs(2), move || {
22        let mut count = counter1.lock().unwrap();
23        *count += 1;
24        println!("[After 2s] Job executed! Counter: {}", *count);
25    })
26    .unwrap();
27
28    // Example 2: Execute once at a specific datetime
29    let target_time = Utc::now() + Duration::seconds(4);
30    println!(
31        "Scheduling job to execute at specific time: {}",
32        target_time.format("%H:%M:%S")
33    );
34    let counter2 = Arc::clone(&counter);
35    cron.add_fn_once(target_time, move || {
36        let mut count = counter2.lock().unwrap();
37        *count += 10;
38        println!("[At {}] Job executed! Counter: {}", target_time.format("%H:%M:%S"), *count);
39    })
40    .unwrap();
41
42    // Example 3: Execute once after 6 seconds
43    println!("Scheduling job to execute after 6 seconds...");
44    let counter3 = Arc::clone(&counter);
45    cron.add_fn_after(std::time::Duration::from_secs(6), move || {
46        let mut count = counter3.lock().unwrap();
47        *count += 100;
48        println!("[After 6s] Job executed! Counter: {}", *count);
49    })
50    .unwrap();
51
52    // Example 4: Mix with recurring job
53    println!("Scheduling recurring job every 3 seconds...");
54    let recurring_counter = Arc::new(Mutex::new(0));
55    let recurring_counter1 = Arc::clone(&recurring_counter);
56    cron.add_fn("*/3 * * * * * *", move || {
57        let mut count = recurring_counter1.lock().unwrap();
58        *count += 1;
59        println!("[Recurring] Executed {} times", *count);
60    })
61    .unwrap();
62
63    // Start the scheduler
64    println!("\nStarting scheduler...\n");
65    cron.start();
66
67    // Let it run for 8 seconds
68    std::thread::sleep(std::time::Duration::from_secs(8));
69
70    // Stop the scheduler
71    cron.stop();
72
73    println!("\n=== Execution Complete ===");
74    println!("Final one-time counter: {}", *counter.lock().unwrap());
75    println!("Final recurring counter: {}", *recurring_counter.lock().unwrap());
76    println!("\nNote: One-time jobs execute exactly once and are automatically removed.");
77}
Source

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

Adds a function to be executed according to the specified cron schedule.

The function will be called without arguments whenever the cron expression matches the current time in the scheduler’s timezone.

§Arguments
  • spec - A cron expression string in the format “sec min hour day month weekday year”
  • f - A function that implements Fn() + Send + Sync + '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::Cron;

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

// Run every second
let job_id = cron.add_fn("* * * * * * *", || {
    println!("Every second!");
}).unwrap();

// Run every day at 9:00 AM
let morning_job = cron.add_fn("0 0 9 * * * *", || {
    println!("Good morning!");
}).unwrap();

// Run every Monday at 10:30 AM
let monday_job = cron.add_fn("0 30 10 * * MON *", || {
    println!("Monday meeting reminder!");
}).unwrap();
Examples found in repository?
examples/simple.rs (line 8)
4fn main() {
5    let local_tz = Local::from_offset(&FixedOffset::east_opt(7).unwrap());
6    let mut cron = cron_tab::Cron::new(local_tz);
7
8    let first_job_id = cron.add_fn("* * * * * * *", print_now).unwrap();
9
10    // start cron in background
11    cron.start();
12
13    cron.add_fn("* * * * * *", move || {
14        println!("add_fn {}", Local::now().to_string());
15    })
16    .unwrap();
17
18    // remove job_test
19    cron.remove(first_job_id);
20
21    std::thread::sleep(std::time::Duration::from_secs(10));
22
23    // stop cron
24    cron.stop();
25}
More examples
Hide additional examples
examples/one_time_execution.rs (lines 56-60)
10fn main() {
11    println!("=== One-Time Task Execution Example ===\n");
12
13    let mut cron = Cron::new(Utc);
14
15    // Shared counter to track execution
16    let counter = Arc::new(Mutex::new(0));
17
18    // Example 1: Execute once after a delay
19    println!("Scheduling job to execute after 2 seconds...");
20    let counter1 = Arc::clone(&counter);
21    cron.add_fn_after(std::time::Duration::from_secs(2), move || {
22        let mut count = counter1.lock().unwrap();
23        *count += 1;
24        println!("[After 2s] Job executed! Counter: {}", *count);
25    })
26    .unwrap();
27
28    // Example 2: Execute once at a specific datetime
29    let target_time = Utc::now() + Duration::seconds(4);
30    println!(
31        "Scheduling job to execute at specific time: {}",
32        target_time.format("%H:%M:%S")
33    );
34    let counter2 = Arc::clone(&counter);
35    cron.add_fn_once(target_time, move || {
36        let mut count = counter2.lock().unwrap();
37        *count += 10;
38        println!("[At {}] Job executed! Counter: {}", target_time.format("%H:%M:%S"), *count);
39    })
40    .unwrap();
41
42    // Example 3: Execute once after 6 seconds
43    println!("Scheduling job to execute after 6 seconds...");
44    let counter3 = Arc::clone(&counter);
45    cron.add_fn_after(std::time::Duration::from_secs(6), move || {
46        let mut count = counter3.lock().unwrap();
47        *count += 100;
48        println!("[After 6s] Job executed! Counter: {}", *count);
49    })
50    .unwrap();
51
52    // Example 4: Mix with recurring job
53    println!("Scheduling recurring job every 3 seconds...");
54    let recurring_counter = Arc::new(Mutex::new(0));
55    let recurring_counter1 = Arc::clone(&recurring_counter);
56    cron.add_fn("*/3 * * * * * *", move || {
57        let mut count = recurring_counter1.lock().unwrap();
58        *count += 1;
59        println!("[Recurring] Executed {} times", *count);
60    })
61    .unwrap();
62
63    // Start the scheduler
64    println!("\nStarting scheduler...\n");
65    cron.start();
66
67    // Let it run for 8 seconds
68    std::thread::sleep(std::time::Duration::from_secs(8));
69
70    // Stop the scheduler
71    cron.stop();
72
73    println!("\n=== Execution Complete ===");
74    println!("Final one-time counter: {}", *counter.lock().unwrap());
75    println!("Final recurring counter: {}", *recurring_counter.lock().unwrap());
76    println!("\nNote: One-time jobs execute exactly once and are automatically removed.");
77}
Source

pub fn add_fn_once<T>(&mut self, datetime: DateTime<Z>, f: T) -> Result<usize>
where T: 'static + Fn() + Send + Sync,

Adds a function to be executed once at a specific datetime.

The function will be called exactly once when the specified time is reached. After execution, the job is automatically removed from the scheduler.

§Arguments
  • datetime - The specific time when the job should execute
  • f - A function that implements Fn() + Send + Sync + '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.

§Behavior with Past Times

If the specified datetime is in the past, the job will execute immediately on the next scheduler iteration. This allows for jobs that may have been scheduled while the system was offline or during startup.

§Examples
use chrono::{Utc, Duration};
use cron_tab::Cron;

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

// Execute once at a specific time
let target_time = Utc::now() + Duration::seconds(10);
let job_id = cron.add_fn_once(target_time, || {
    println!("This runs once at the specified time!");
}).unwrap();
Examples found in repository?
examples/one_time_execution.rs (lines 35-39)
10fn main() {
11    println!("=== One-Time Task Execution Example ===\n");
12
13    let mut cron = Cron::new(Utc);
14
15    // Shared counter to track execution
16    let counter = Arc::new(Mutex::new(0));
17
18    // Example 1: Execute once after a delay
19    println!("Scheduling job to execute after 2 seconds...");
20    let counter1 = Arc::clone(&counter);
21    cron.add_fn_after(std::time::Duration::from_secs(2), move || {
22        let mut count = counter1.lock().unwrap();
23        *count += 1;
24        println!("[After 2s] Job executed! Counter: {}", *count);
25    })
26    .unwrap();
27
28    // Example 2: Execute once at a specific datetime
29    let target_time = Utc::now() + Duration::seconds(4);
30    println!(
31        "Scheduling job to execute at specific time: {}",
32        target_time.format("%H:%M:%S")
33    );
34    let counter2 = Arc::clone(&counter);
35    cron.add_fn_once(target_time, move || {
36        let mut count = counter2.lock().unwrap();
37        *count += 10;
38        println!("[At {}] Job executed! Counter: {}", target_time.format("%H:%M:%S"), *count);
39    })
40    .unwrap();
41
42    // Example 3: Execute once after 6 seconds
43    println!("Scheduling job to execute after 6 seconds...");
44    let counter3 = Arc::clone(&counter);
45    cron.add_fn_after(std::time::Duration::from_secs(6), move || {
46        let mut count = counter3.lock().unwrap();
47        *count += 100;
48        println!("[After 6s] Job executed! Counter: {}", *count);
49    })
50    .unwrap();
51
52    // Example 4: Mix with recurring job
53    println!("Scheduling recurring job every 3 seconds...");
54    let recurring_counter = Arc::new(Mutex::new(0));
55    let recurring_counter1 = Arc::clone(&recurring_counter);
56    cron.add_fn("*/3 * * * * * *", move || {
57        let mut count = recurring_counter1.lock().unwrap();
58        *count += 1;
59        println!("[Recurring] Executed {} times", *count);
60    })
61    .unwrap();
62
63    // Start the scheduler
64    println!("\nStarting scheduler...\n");
65    cron.start();
66
67    // Let it run for 8 seconds
68    std::thread::sleep(std::time::Duration::from_secs(8));
69
70    // Stop the scheduler
71    cron.stop();
72
73    println!("\n=== Execution Complete ===");
74    println!("Final one-time counter: {}", *counter.lock().unwrap());
75    println!("Final recurring counter: {}", *recurring_counter.lock().unwrap());
76    println!("\nNote: One-time jobs execute exactly once and are automatically removed.");
77}
Source

pub fn add_fn_after<T>(&mut self, delay: Duration, f: T) -> Result<usize>
where T: 'static + Fn() + Send + Sync,

Adds a function to be executed once after a specified delay.

The function will be called exactly once after the specified duration has passed. After execution, the job is automatically removed from the scheduler.

§Arguments
  • delay - The duration to wait before executing the job
  • f - A function that implements Fn() + Send + Sync + '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.

§Examples
use std::time::Duration;
use chrono::Utc;
use cron_tab::Cron;

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

// Execute once after 30 seconds
let job_id = cron.add_fn_after(Duration::from_secs(30), || {
    println!("This runs once after 30 seconds!");
}).unwrap();

// Execute after 5 minutes
let delayed_job = cron.add_fn_after(Duration::from_secs(300), || {
    println!("This runs after 5 minutes!");
}).unwrap();
Examples found in repository?
examples/one_time_execution.rs (lines 21-25)
10fn main() {
11    println!("=== One-Time Task Execution Example ===\n");
12
13    let mut cron = Cron::new(Utc);
14
15    // Shared counter to track execution
16    let counter = Arc::new(Mutex::new(0));
17
18    // Example 1: Execute once after a delay
19    println!("Scheduling job to execute after 2 seconds...");
20    let counter1 = Arc::clone(&counter);
21    cron.add_fn_after(std::time::Duration::from_secs(2), move || {
22        let mut count = counter1.lock().unwrap();
23        *count += 1;
24        println!("[After 2s] Job executed! Counter: {}", *count);
25    })
26    .unwrap();
27
28    // Example 2: Execute once at a specific datetime
29    let target_time = Utc::now() + Duration::seconds(4);
30    println!(
31        "Scheduling job to execute at specific time: {}",
32        target_time.format("%H:%M:%S")
33    );
34    let counter2 = Arc::clone(&counter);
35    cron.add_fn_once(target_time, move || {
36        let mut count = counter2.lock().unwrap();
37        *count += 10;
38        println!("[At {}] Job executed! Counter: {}", target_time.format("%H:%M:%S"), *count);
39    })
40    .unwrap();
41
42    // Example 3: Execute once after 6 seconds
43    println!("Scheduling job to execute after 6 seconds...");
44    let counter3 = Arc::clone(&counter);
45    cron.add_fn_after(std::time::Duration::from_secs(6), move || {
46        let mut count = counter3.lock().unwrap();
47        *count += 100;
48        println!("[After 6s] Job executed! Counter: {}", *count);
49    })
50    .unwrap();
51
52    // Example 4: Mix with recurring job
53    println!("Scheduling recurring job every 3 seconds...");
54    let recurring_counter = Arc::new(Mutex::new(0));
55    let recurring_counter1 = Arc::clone(&recurring_counter);
56    cron.add_fn("*/3 * * * * * *", move || {
57        let mut count = recurring_counter1.lock().unwrap();
58        *count += 1;
59        println!("[Recurring] Executed {} times", *count);
60    })
61    .unwrap();
62
63    // Start the scheduler
64    println!("\nStarting scheduler...\n");
65    cron.start();
66
67    // Let it run for 8 seconds
68    std::thread::sleep(std::time::Duration::from_secs(8));
69
70    // Stop the scheduler
71    cron.stop();
72
73    println!("\n=== Execution Complete ===");
74    println!("Final one-time counter: {}", *counter.lock().unwrap());
75    println!("Final recurring counter: {}", *recurring_counter.lock().unwrap());
76    println!("\nNote: One-time jobs execute exactly once and are automatically removed.");
77}
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::Cron;

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

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

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

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

pub 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.

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

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

cron.start();
 
// Later, remove the job
cron.remove(job_id);
Examples found in repository?
examples/simple.rs (line 19)
4fn main() {
5    let local_tz = Local::from_offset(&FixedOffset::east_opt(7).unwrap());
6    let mut cron = cron_tab::Cron::new(local_tz);
7
8    let first_job_id = cron.add_fn("* * * * * * *", print_now).unwrap();
9
10    // start cron in background
11    cron.start();
12
13    cron.add_fn("* * * * * *", move || {
14        println!("add_fn {}", Local::now().to_string());
15    })
16    .unwrap();
17
18    // remove job_test
19    cron.remove(first_job_id);
20
21    std::thread::sleep(std::time::Duration::from_secs(10));
22
23    // stop cron
24    cron.stop();
25}
Source

pub fn stop(&self)

Stops the cron scheduler.

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

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

let mut cron = Cron::new(Utc);
cron.add_fn("* * * * * * *", || println!("Hello")).unwrap();
cron.start();

// Later, stop the scheduler
cron.stop();
Examples found in repository?
examples/simple.rs (line 24)
4fn main() {
5    let local_tz = Local::from_offset(&FixedOffset::east_opt(7).unwrap());
6    let mut cron = cron_tab::Cron::new(local_tz);
7
8    let first_job_id = cron.add_fn("* * * * * * *", print_now).unwrap();
9
10    // start cron in background
11    cron.start();
12
13    cron.add_fn("* * * * * *", move || {
14        println!("add_fn {}", Local::now().to_string());
15    })
16    .unwrap();
17
18    // remove job_test
19    cron.remove(first_job_id);
20
21    std::thread::sleep(std::time::Duration::from_secs(10));
22
23    // stop cron
24    cron.stop();
25}
More examples
Hide additional examples
examples/one_time_execution.rs (line 71)
10fn main() {
11    println!("=== One-Time Task Execution Example ===\n");
12
13    let mut cron = Cron::new(Utc);
14
15    // Shared counter to track execution
16    let counter = Arc::new(Mutex::new(0));
17
18    // Example 1: Execute once after a delay
19    println!("Scheduling job to execute after 2 seconds...");
20    let counter1 = Arc::clone(&counter);
21    cron.add_fn_after(std::time::Duration::from_secs(2), move || {
22        let mut count = counter1.lock().unwrap();
23        *count += 1;
24        println!("[After 2s] Job executed! Counter: {}", *count);
25    })
26    .unwrap();
27
28    // Example 2: Execute once at a specific datetime
29    let target_time = Utc::now() + Duration::seconds(4);
30    println!(
31        "Scheduling job to execute at specific time: {}",
32        target_time.format("%H:%M:%S")
33    );
34    let counter2 = Arc::clone(&counter);
35    cron.add_fn_once(target_time, move || {
36        let mut count = counter2.lock().unwrap();
37        *count += 10;
38        println!("[At {}] Job executed! Counter: {}", target_time.format("%H:%M:%S"), *count);
39    })
40    .unwrap();
41
42    // Example 3: Execute once after 6 seconds
43    println!("Scheduling job to execute after 6 seconds...");
44    let counter3 = Arc::clone(&counter);
45    cron.add_fn_after(std::time::Duration::from_secs(6), move || {
46        let mut count = counter3.lock().unwrap();
47        *count += 100;
48        println!("[After 6s] Job executed! Counter: {}", *count);
49    })
50    .unwrap();
51
52    // Example 4: Mix with recurring job
53    println!("Scheduling recurring job every 3 seconds...");
54    let recurring_counter = Arc::new(Mutex::new(0));
55    let recurring_counter1 = Arc::clone(&recurring_counter);
56    cron.add_fn("*/3 * * * * * *", move || {
57        let mut count = recurring_counter1.lock().unwrap();
58        *count += 1;
59        println!("[Recurring] Executed {} times", *count);
60    })
61    .unwrap();
62
63    // Start the scheduler
64    println!("\nStarting scheduler...\n");
65    cron.start();
66
67    // Let it run for 8 seconds
68    std::thread::sleep(std::time::Duration::from_secs(8));
69
70    // Stop the scheduler
71    cron.stop();
72
73    println!("\n=== Execution Complete ===");
74    println!("Final one-time counter: {}", *counter.lock().unwrap());
75    println!("Final recurring counter: {}", *recurring_counter.lock().unwrap());
76    println!("\nNote: One-time jobs execute exactly once and are automatically removed.");
77}
Source

pub fn start(&mut self)

Starts the cron scheduler in a background thread.

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

§Thread Safety

The scheduler runs in its own thread and spawns additional threads for each job execution. This ensures that long-running jobs don’t block the scheduler or other jobs.

§Examples
use chrono::Utc;
use cron_tab::Cron;
use std::time::Duration;

let mut cron = Cron::new(Utc);
cron.add_fn("*/2 * * * * * *", || {
    println!("Job executed every 2 seconds");
}).unwrap();

// Start the scheduler
cron.start();

// The main thread can continue with other work
std::thread::sleep(Duration::from_secs(10));

// Stop the scheduler
cron.stop();
Examples found in repository?
examples/simple.rs (line 11)
4fn main() {
5    let local_tz = Local::from_offset(&FixedOffset::east_opt(7).unwrap());
6    let mut cron = cron_tab::Cron::new(local_tz);
7
8    let first_job_id = cron.add_fn("* * * * * * *", print_now).unwrap();
9
10    // start cron in background
11    cron.start();
12
13    cron.add_fn("* * * * * *", move || {
14        println!("add_fn {}", Local::now().to_string());
15    })
16    .unwrap();
17
18    // remove job_test
19    cron.remove(first_job_id);
20
21    std::thread::sleep(std::time::Duration::from_secs(10));
22
23    // stop cron
24    cron.stop();
25}
More examples
Hide additional examples
examples/one_time_execution.rs (line 65)
10fn main() {
11    println!("=== One-Time Task Execution Example ===\n");
12
13    let mut cron = Cron::new(Utc);
14
15    // Shared counter to track execution
16    let counter = Arc::new(Mutex::new(0));
17
18    // Example 1: Execute once after a delay
19    println!("Scheduling job to execute after 2 seconds...");
20    let counter1 = Arc::clone(&counter);
21    cron.add_fn_after(std::time::Duration::from_secs(2), move || {
22        let mut count = counter1.lock().unwrap();
23        *count += 1;
24        println!("[After 2s] Job executed! Counter: {}", *count);
25    })
26    .unwrap();
27
28    // Example 2: Execute once at a specific datetime
29    let target_time = Utc::now() + Duration::seconds(4);
30    println!(
31        "Scheduling job to execute at specific time: {}",
32        target_time.format("%H:%M:%S")
33    );
34    let counter2 = Arc::clone(&counter);
35    cron.add_fn_once(target_time, move || {
36        let mut count = counter2.lock().unwrap();
37        *count += 10;
38        println!("[At {}] Job executed! Counter: {}", target_time.format("%H:%M:%S"), *count);
39    })
40    .unwrap();
41
42    // Example 3: Execute once after 6 seconds
43    println!("Scheduling job to execute after 6 seconds...");
44    let counter3 = Arc::clone(&counter);
45    cron.add_fn_after(std::time::Duration::from_secs(6), move || {
46        let mut count = counter3.lock().unwrap();
47        *count += 100;
48        println!("[After 6s] Job executed! Counter: {}", *count);
49    })
50    .unwrap();
51
52    // Example 4: Mix with recurring job
53    println!("Scheduling recurring job every 3 seconds...");
54    let recurring_counter = Arc::new(Mutex::new(0));
55    let recurring_counter1 = Arc::clone(&recurring_counter);
56    cron.add_fn("*/3 * * * * * *", move || {
57        let mut count = recurring_counter1.lock().unwrap();
58        *count += 1;
59        println!("[Recurring] Executed {} times", *count);
60    })
61    .unwrap();
62
63    // Start the scheduler
64    println!("\nStarting scheduler...\n");
65    cron.start();
66
67    // Let it run for 8 seconds
68    std::thread::sleep(std::time::Duration::from_secs(8));
69
70    // Stop the scheduler
71    cron.stop();
72
73    println!("\n=== Execution Complete ===");
74    println!("Final one-time counter: {}", *counter.lock().unwrap());
75    println!("Final recurring counter: {}", *recurring_counter.lock().unwrap());
76    println!("\nNote: One-time jobs execute exactly once and are automatically removed.");
77}
Source

pub fn start_blocking(&mut self)

Runs the scheduler in the current thread (blocking).

This method runs the main scheduler loop in the current thread, making it block until stop is called. This is useful when you want to run the scheduler as the main thread of your application.

§Behavior

The scheduler will:

  1. Calculate the next execution time for all jobs
  2. Sleep until the next job is due
  3. Execute all due jobs in separate threads
  4. Repeat until stopped
§Examples
use chrono::Utc;
use cron_tab::Cron;

let mut cron = Cron::new(Utc);
cron.add_fn("0 0 * * * * *", || {
    println!("Top of the hour!");
}).unwrap();

// This will block until stop() is called from another thread
cron.start_blocking();

Trait Implementations§

Source§

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

Source§

fn clone(&self) -> Cron<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 Cron<Z>
where Z: TimeZone + Sync + Send + '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 Cron<Z>
where Z: Freeze,

§

impl<Z> RefUnwindSafe for Cron<Z>
where Z: RefUnwindSafe,

§

impl<Z> Send for Cron<Z>

§

impl<Z> Sync for Cron<Z>

§

impl<Z> Unpin for Cron<Z>
where Z: Unpin, <Z as TimeZone>::Offset: Unpin,

§

impl<Z> UnwindSafe for Cron<Z>
where Z: UnwindSafe,

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.