Add Every, a tool to create recurring jobs

This commit is contained in:
asonix 2019-05-27 19:23:25 -05:00
parent 1f10095269
commit ffa61b3c33
3 changed files with 58 additions and 2 deletions

54
jobs-actix/src/every.rs Normal file
View file

@ -0,0 +1,54 @@
use std::time::Duration;
use super::{Job, QueueHandle};
use actix::{Actor, AsyncContext, Context};
use log::error;
/// A type used to schedule recurring jobs.
///
/// ```rust,ignore
/// let server = ServerConfig::new(storage).start();
/// Every::new(server, Duration::from_secs(60 * 30), MyJob::new()).start();
/// ```
pub struct Every<J>
where
J: Job + Clone + 'static,
{
spawner: QueueHandle,
duration: Duration,
job: J,
}
impl<J> Every<J>
where
J: Job + Clone + 'static,
{
pub fn new(spawner: QueueHandle, duration: Duration, job: J) -> Self {
Every {
spawner,
duration,
job,
}
}
}
impl<J> Actor for Every<J>
where
J: Job + Clone + 'static,
{
type Context = Context<Self>;
fn started(&mut self, ctx: &mut Self::Context) {
match self.spawner.queue(self.job.clone()) {
Ok(_) => (),
Err(_) => error!("Failed to queue job"),
};
ctx.run_interval(self.duration.clone(), move |actor, _| {
match actor.spawner.queue(actor.job.clone()) {
Ok(_) => (),
Err(_) => error!("Failed to queue job"),
}
});
}
}

View file

@ -5,11 +5,13 @@ use background_jobs_core::{Job, Processor, ProcessorMap, Stats, Storage};
use failure::Error; use failure::Error;
use futures::Future; use futures::Future;
mod every;
mod pinger; mod pinger;
mod server; mod server;
mod storage; mod storage;
mod worker; mod worker;
pub use self::{server::Server, worker::LocalWorker};
pub use self::{every::Every, server::Server, worker::LocalWorker};
use self::{ use self::{
pinger::Pinger, pinger::Pinger,

View file

@ -202,7 +202,7 @@ pub use background_jobs_core::{
}; };
#[cfg(feature = "background-jobs-actix")] #[cfg(feature = "background-jobs-actix")]
pub use background_jobs_actix::{QueueHandle, ServerConfig, WorkerConfig}; pub use background_jobs_actix::{Every, QueueHandle, ServerConfig, WorkerConfig};
#[cfg(feature = "background-jobs-sled-storage")] #[cfg(feature = "background-jobs-sled-storage")]
pub mod sled_storage { pub mod sled_storage {