use chrono::{prelude::*, Duration as ChronoDuration}; use job_scheduler::{Job, JobScheduler}; // use once_cell::sync::Lazy; use sqlx::{postgres::PgPoolOptions, Pool, Postgres}; use tasks::import_posts::{self, import_posts}; use std::env; use std::time::Duration; //mod config; mod tasks; mod utils; pub struct TaskManager<'a> { pool: Pool, jobs: Vec, last_activated: Option>, last_job: Option, scheduler: job_scheduler::JobScheduler<'a>, } pub struct TaskLog { task_log_id: u8, task_id: u8, created_at: chrono::DateTime, task_status: TaskStatus, } enum TaskStatus { Pending, Completed, Failed, } #[derive(Debug, sqlx::FromRow, Clone)] pub struct TaskJob { pub task_id: i32, pub task_name: String, pub schedule: String, pub is_active: bool, pub created_at: chrono::DateTime, pub deleted_at: Option>, } #[tokio::main] async fn main() { println!("Hello, world!"); dotenvy::dotenv().unwrap(); let database_url = env::var("DATABASE_URL").expect("Environment variable DATABASE_URL is not found"); let pool = PgPoolOptions::new() .max_connections(10) .acquire_timeout(Duration::from_secs(5)) .connect(&database_url) .await .expect("Failed to connect to the database"); let mut manager = TaskManager::new(pool); manager.register_jobs().await; loop { manager.scheduler.tick(); std::thread::sleep(std::time::Duration::from_millis(500)); } } impl<'a> TaskManager<'a> { fn new(pool: Pool) -> Self { TaskManager { pool, jobs: Vec::new(), last_activated: None, last_job: None, scheduler: job_scheduler::JobScheduler::new(), } } pub async fn register_jobs(&self) { // let jobs: Vec = Vec::new(); let results = sqlx::query_as::<_, TaskJob>("SELECT task_id, task_name, schedule, is_active, created_at, deleted_at FROM tasks WHERE is_active = true AND deleted_at IS NULL") .fetch_all(&self.pool) .await .unwrap(); let mut scheduler = job_scheduler::JobScheduler::new(); for result in results { let r = result.clone(); scheduler.add(job_scheduler::Job::new(r.schedule.parse().unwrap(), move || { println!("Registering job: {}", r.task_name); match r.task_id { 1 => async { import_posts::import_posts("/app", &self.pool).await }, _ => panic!(), }; })); } } }