Skip to main content

pakem/core/schedule/
mod.rs

1use crate::core::application::AppState;
2use std::sync::Arc;
3use tokio_cron_scheduler::{Job, JobScheduler};
4
5/// Lumina Scheduler — wrapper untuk tokio-cron-scheduler.
6/// Memungkinkan penjadwalan tugas (cron jobs) langsung dari aplikasi.
7pub struct Scheduler {
8    sched: JobScheduler,
9    state: Arc<AppState>,
10}
11
12impl Scheduler {
13    /// Buat instance scheduler baru.
14    pub async fn new(state: Arc<AppState>) -> Self {
15        let sched = JobScheduler::new()
16            .await
17            .expect("Gagal menginisialisasi Scheduler");
18        Self { sched, state }
19    }
20
21    /// Jadwalkan tugas menggunakan ekspresi cron secara langsung.
22    pub async fn cron<F, Fut>(&self, cron_expr: &str, task_fn: F) -> Result<(), String>
23    where
24        F: Fn() -> Fut + Send + Sync + 'static,
25        Fut: std::future::Future<Output = ()> + Send + 'static,
26    {
27        let job = Job::new_async(cron_expr, move |_uuid, _l| {
28            let fut = task_fn();
29            Box::pin(async move {
30                fut.await;
31            })
32        })
33        .map_err(|e| format!("Cron error: {}", e))?;
34
35        self.sched
36            .add(job)
37            .await
38            .map_err(|e| format!("Scheduler error: {}", e))?;
39        Ok(())
40    }
41
42    /// Entry point untuk membuat tugas dengan API yang fluent.
43    pub fn call<F, Fut>(&self, task_fn: F) -> ScheduledTask<'_, F, Fut>
44    where
45        F: Fn() -> Fut + Send + Sync + 'static,
46        Fut: std::future::Future<Output = ()> + Send + 'static,
47    {
48        ScheduledTask {
49            scheduler: self,
50            task_fn,
51            _phantom: std::marker::PhantomData,
52        }
53    }
54
55    /// Mulai menjalankan scheduler di background.
56    pub async fn run(&self) {
57        if let Err(e) = self.sched.start().await {
58            eprintln!("❌ Gagal menjalankan Scheduler: {}", e);
59        } else {
60            println!("⏰ Task Scheduler started.");
61        }
62    }
63
64    /// Akses ke AppState dari dalam job.
65    pub fn state(&self) -> Arc<AppState> {
66        self.state.clone()
67    }
68}
69
70/// Helper untuk API penjadwalan yang lebih manusiawi.
71pub struct ScheduledTask<'a, F, Fut> {
72    scheduler: &'a Scheduler,
73    task_fn: F,
74    _phantom: std::marker::PhantomData<Fut>,
75}
76
77impl<'a, F, Fut> ScheduledTask<'a, F, Fut>
78where
79    F: Fn() -> Fut + Send + Sync + 'static,
80    Fut: std::future::Future<Output = ()> + Send + 'static,
81{
82    pub async fn every_second(self) -> Result<(), String> {
83        self.scheduler.cron("* * * * * *", self.task_fn).await
84    }
85
86    pub async fn every_minute(self) -> Result<(), String> {
87        self.scheduler.cron("0 * * * * *", self.task_fn).await
88    }
89
90    pub async fn every_five_minutes(self) -> Result<(), String> {
91        self.scheduler.cron("0 */5 * * * *", self.task_fn).await
92    }
93
94    pub async fn hourly(self) -> Result<(), String> {
95        self.scheduler.cron("0 0 * * * *", self.task_fn).await
96    }
97
98    pub async fn daily(self) -> Result<(), String> {
99        self.scheduler.cron("0 0 0 * * *", self.task_fn).await
100    }
101
102    pub async fn daily_at(self, time: &str) -> Result<(), String> {
103        // time format: "HH:MM"
104        let parts: Vec<&str> = time.split(':').collect();
105        if parts.len() != 2 {
106            return Err("Format waktu harus HH:MM".to_string());
107        }
108        let cron = format!("0 {} {} * * *", parts[1], parts[0]);
109        self.scheduler.cron(&cron, self.task_fn).await
110    }
111
112    pub async fn weekly(self) -> Result<(), String> {
113        self.scheduler.cron("0 0 0 * * 0", self.task_fn).await
114    }
115
116    pub async fn monthly(self) -> Result<(), String> {
117        self.scheduler.cron("0 0 0 1 * *", self.task_fn).await
118    }
119}