pub struct Cron<Z>{ /* 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 implementsTimeZone + 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>
Implementation of the synchronous cron scheduler.
impl<Z> Cron<Z>
Implementation of the synchronous cron scheduler.
Sourcepub fn new(tz: Z) -> Cron<Z>
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?
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
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}Sourcepub fn add_fn<T>(&mut self, spec: &str, f: T) -> Result<usize>
pub fn add_fn<T>(&mut self, spec: &str, f: T) -> Result<usize>
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 implementsFn() + 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?
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
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}Sourcepub fn add_fn_once<T>(&mut self, datetime: DateTime<Z>, f: T) -> Result<usize>
pub fn add_fn_once<T>(&mut self, datetime: DateTime<Z>, f: T) -> Result<usize>
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 executef- A function that implementsFn() + 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?
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}Sourcepub fn add_fn_after<T>(&mut self, delay: Duration, f: T) -> Result<usize>
pub fn add_fn_after<T>(&mut self, delay: Duration, f: T) -> Result<usize>
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 jobf- A function that implementsFn() + 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?
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}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::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();Sourcepub fn remove(&self, id: usize)
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 byadd_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?
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}Sourcepub fn stop(&self)
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?
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
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}Sourcepub fn start(&mut self)
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?
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
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}Sourcepub fn start_blocking(&mut self)
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:
- Calculate the next execution time for all jobs
- Sleep until the next job is due
- Execute all due jobs in separate threads
- 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();