diff --git a/rwf/src/job/mod.rs b/rwf/src/job/mod.rs index 87b559d1..ee6a420d 100644 --- a/rwf/src/job/mod.rs +++ b/rwf/src/job/mod.rs @@ -11,5 +11,5 @@ pub mod worker; pub use clock::Clock; pub use cron::Cron; pub use error::Error; -pub use model::{Job, JobHandler, JobModel}; +pub use model::{queue, queue_delay, Job, JobHandler, JobModel}; pub use worker::Worker; diff --git a/rwf/src/job/model.rs b/rwf/src/job/model.rs index d45d96d0..1be7c6fe 100644 --- a/rwf/src/job/model.rs +++ b/rwf/src/job/model.rs @@ -1,6 +1,7 @@ use crate::colors::MaybeColorize; use crate::job::{clock::ScheduledJob, Error}; use crate::model::{get_connection, FromRow, Model, Scope, ToValue, Value}; +use serde::Serialize; use time::{Duration, OffsetDateTime}; use async_trait::async_trait; @@ -217,3 +218,35 @@ impl JobHandler { Self { job: Box::new(job) } } } + +pub async fn queue(job: &T) -> Result<(), Error> { + let mut conn = get_connection().await?; + let args = serde_json::to_value(job)?; + + JobModel::new(job.job_name(), args) + .save() + .execute(&mut conn) + .await?; + + info!("job {} scheduled to run now", job.job_name().green()); + + Ok(()) +} + +pub async fn queue_delay(job: &T, delay: Duration) -> Result<(), Error> { + let mut conn = get_connection().await?; + let args = serde_json::to_value(job)?; + + JobModel::new_with_delay(job.job_name(), args, delay) + .save() + .execute(&mut conn) + .await?; + + info!( + "job {} scheduled to run in {}s", + job.job_name().green(), + delay.whole_seconds() + ); + + Ok(()) +}