Skip to main content

one_time_execution/
one_time_execution.rs

1//! Example demonstrating one-time task execution at a specific time or after a delay.
2//!
3//! This example shows how to use the `add_fn_once` and `add_fn_after` methods
4//! to schedule tasks that execute exactly once.
5
6use chrono::{Duration, Utc};
7use cron_tab::Cron;
8use std::sync::{Arc, Mutex};
9
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}