comrade/examples/cron.rs
2025-03-10 18:43:32 +01:00

59 lines
1.4 KiB
Rust

use comrade::{
cron::{Cron, Schedule},
datetime_in, defer, delay,
service::ServiceManager,
};
use std::time::Duration;
fn main() {
env_logger::init();
let s = ServiceManager::new();
// Init Cron Manager
let cron = Cron::new();
// Add Cron Task
cron.add_task("4_sec", Schedule::Every(Duration::from_secs(4)), || {
println!("I run every 4 at {}", chrono::Utc::now());
});
cron.add_task("2_sec", Schedule::Every(Duration::from_secs(2)), || {
println!("I run every 2 seconds at {}", chrono::Utc::now());
});
cron.add_task(
"daily",
Schedule::Every(Duration::from_secs(60 * 60 * 24)),
|| {
println!("I run daily");
},
);
// Start running the Cron Manager
let (s, cron) = s.register_cron(cron.into());
let s = s.spawn();
defer!(|| {
s.join().unwrap();
});
// Add another Cron Task after running the manager dynamically
cron.add_task(
"future_task",
Schedule::At(datetime_in(Duration::from_secs(2))),
|| {
println!("I am in the future");
},
);
// Functionally the same as above
cron.run_at(datetime_in(Duration::from_secs(3)), || {
println!("The Future");
});
// ---
// Delayed execution
delay(Duration::from_secs(4), || {
println!("I will run in 4 seconds from now on!");
});
}