#![cfg(feature = "scheduler")]
use cano::prelude::*;
use tokio::time::Duration;
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
enum TaskState {
Start,
Complete,
}
#[derive(Clone)]
struct DailyTask;
#[task(state = TaskState)]
impl DailyTask {
async fn run_bare(&self) -> Result<TaskResult<TaskState>, CanoError> {
println!(
"Daily task executed at {}",
chrono::Utc::now().format("%H:%M:%S")
);
Ok(TaskResult::Single(TaskState::Complete))
}
}
#[derive(Clone)]
struct HourlyTask;
#[task(state = TaskState)]
impl HourlyTask {
async fn run_bare(&self) -> Result<TaskResult<TaskState>, CanoError> {
println!(
"Hourly task executed at {}",
chrono::Utc::now().format("%H:%M:%S")
);
Ok(TaskResult::Single(TaskState::Complete))
}
}
#[derive(Clone)]
struct FrequentTask;
#[task(state = TaskState)]
impl FrequentTask {
async fn run_bare(&self) -> Result<TaskResult<TaskState>, CanoError> {
println!(
"Frequent task executed at {}",
chrono::Utc::now().format("%H:%M:%S")
);
Ok(TaskResult::Single(TaskState::Complete))
}
}
#[tokio::main]
async fn main() -> CanoResult<()> {
println!("Duration-Based Scheduling Example");
println!("====================================");
let mut scheduler = Scheduler::new();
let store = MemoryStore::new();
let daily_flow = Workflow::new(Resources::new().insert("store", store.clone()))
.register(TaskState::Start, DailyTask)
.add_exit_state(TaskState::Complete);
let hourly_flow = Workflow::new(Resources::new().insert("store", store.clone()))
.register(TaskState::Start, HourlyTask)
.add_exit_state(TaskState::Complete);
let frequent_flow = Workflow::new(Resources::new().insert("store", store.clone()))
.register(TaskState::Start, FrequentTask)
.add_exit_state(TaskState::Complete);
scheduler.every(
"daily_task",
daily_flow,
TaskState::Start,
Duration::from_secs(4),
)?; scheduler.every(
"hourly_task",
hourly_flow,
TaskState::Start,
Duration::from_secs(2),
)?; scheduler.every(
"frequent_task",
frequent_flow,
TaskState::Start,
Duration::from_secs(1),
)?;
println!("Scheduled workflows:");
println!(" Daily task: Every 4 seconds (simulated)");
println!(" Hourly task: Every 2 seconds (simulated)");
println!(" Frequent task: Every 1 second");
println!();
let running = scheduler.start().await?;
println!("Scheduler started! Running for 10 seconds...");
tokio::time::sleep(Duration::from_secs(10)).await;
running.stop().await?;
println!("Scheduler stopped gracefully");
Ok(())
}