1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293
#![forbid(unsafe_code, non_ascii_idents)]
#![deny(
rust_2018_idioms,
rust_2021_compatibility,
noop_method_call,
pointer_structural_match,
trivial_casts,
trivial_numeric_casts,
unused_import_braces,
unused,
clippy::cast_lossless,
clippy::clone_on_ref_ptr,
clippy::complexity,
clippy::correctness,
clippy::equatable_if_let,
clippy::float_cmp_const,
clippy::inefficient_to_string,
clippy::iter_on_empty_collections,
clippy::iter_on_single_items,
clippy::linkedlist,
clippy::macro_use_imports,
clippy::manual_assert,
clippy::manual_instant_elapsed,
clippy::manual_string_new,
clippy::match_wildcard_for_single_variants,
clippy::mem_forget,
clippy::nursery,
clippy::perf,
clippy::string_add_assign,
clippy::string_to_string,
clippy::style,
clippy::suspicious,
clippy::unnecessary_join,
clippy::unnecessary_self_imports,
clippy::unused_async,
clippy::verbose_file_reads,
clippy::zero_sized_map_values
)]
//! # JobScheduler
//!
//! A simple cron-like job scheduling library for Rust.
//!
//! ## Usage
//!
//! Be sure to add the job_scheduler_ng crate to your `Cargo.toml`:
//!
//! ```toml
//! [dependencies]
//! job_scheduler_ng = "*"
//! ```
//!
//! Creating a schedule for a job is done using the `FromStr` impl for the
//! `Schedule` type of the [cron](https://github.com/zslayton/cron) library.
//!
//! The scheduling format is as follows:
//!
//! ```text
//! sec min hour day of month month day of week year
//! * * * * * * *
//! ```
//!
//! Note that the year may be omitted.
//!
//! Comma separated values such as `5,8,10` represent more than one time
//! value. So for example, a schedule of `0 2,14,26 * * * *` would execute
//! on the 2nd, 14th, and 26th minute of every hour.
//!
//! Ranges can be specified with a dash. A schedule of `0 0 * 5-10 * *`
//! would execute once per hour but only on day 5 through 10 of the month.
//!
//! Day of the week can be specified as an abbreviation or the full name.
//! A schedule of `0 0 6 * * Sun,Sat` would execute at 6am on Sunday and
//! Saturday.
//!
//! A simple usage example:
//!
//! ```rust,ignore
//! use job_scheduler_ng::{JobScheduler, Job};
//! use core::time::Duration;
//!
//! fn main() {
//! let mut sched = JobScheduler::new();
//!
//! sched.add(Job::new("0/10 * * * * *".parse().unwrap(), || {
//! println!("I get executed every 10th second!");
//! }));
//!
//! sched.add(Job::new("*/4 * * * * *".parse().unwrap(), || {
//! println!("I get executed every 4 seconds!");
//! }));
//!
//! loop {
//! sched.tick();
//! std::thread::sleep(Duration::from_millis(500));
//! }
//! }
//! ```
use chrono::{offset, DateTime, Duration, Utc};
pub use cron::Schedule;
pub use uuid::Uuid;
/// A schedulable `Job`.
pub struct Job<'a> {
schedule: Schedule,
run: Box<dyn (FnMut()) + Send + 'a>,
last_tick: Option<DateTime<Utc>>,
limit_missed_runs: usize,
job_id: Uuid,
}
impl<'a> Job<'a> {
/// Create a new job.
///
/// ```rust,ignore
/// // Run at second 0 of the 15th minute of the 6th, 8th, and 10th hour
/// // of any day in March and June that is a Friday of the year 2017.
/// let s: Schedule = "0 15 6,8,10 * Mar,Jun Fri 2017".into().unwrap();
/// Job::new(s, || println!("I have a complex schedule...") );
/// ```
#[inline]
pub fn new<T>(schedule: Schedule, run: T) -> Self
where
T: FnMut() + Send + 'a,
{
Self {
schedule,
run: Box::new(run),
last_tick: None,
limit_missed_runs: 1,
job_id: Uuid::new_v4(),
}
}
fn tick(&mut self) {
let now = Utc::now();
if self.last_tick.is_none() {
self.last_tick = Some(now);
return;
}
if self.limit_missed_runs > 0 {
for event in self
.schedule
.after(&self.last_tick.unwrap())
.take(self.limit_missed_runs)
{
if event > now {
break;
}
(self.run)();
}
} else {
for event in self.schedule.after(&self.last_tick.unwrap()) {
if event > now {
break;
}
(self.run)();
}
}
self.last_tick = Some(now);
}
/// Set the limit for missed jobs in the case of delayed runs. Setting to 0 means unlimited.
///
/// ```rust,ignore
/// let mut job = Job::new("0/1 * * * * *".parse().unwrap(), || {
/// println!("I get executed every 1 seconds!");
/// });
/// job.limit_missed_runs(99);
/// ```
#[inline]
pub fn limit_missed_runs(&mut self, limit: usize) {
self.limit_missed_runs = limit;
}
/// Set last tick to force re-running of missed runs.
///
/// ```rust,ignore
/// let mut job = Job::new("0/1 * * * * *".parse().unwrap(), || {
/// println!("I get executed every 1 seconds!");
/// });
/// job.last_tick(Some(Utc::now()));
/// ```
#[inline]
pub fn last_tick(&mut self, last_tick: Option<DateTime<Utc>>) {
self.last_tick = last_tick;
}
}
#[derive(Default)]
/// The JobScheduler contains and executes the scheduled jobs.
pub struct JobScheduler<'a> {
jobs: Vec<Job<'a>>,
}
impl<'a> JobScheduler<'a> {
/// Create a new `JobScheduler`.
#[inline]
#[must_use]
pub const fn new() -> Self {
Self { jobs: Vec::new() }
}
/// Add a job to the `JobScheduler`
///
/// ```rust,ignore
/// let mut sched = JobScheduler::new();
/// sched.add(Job::new("1/10 * * * * *".parse().unwrap(), || {
/// println!("I get executed every 10 seconds!");
/// }));
/// ```
#[inline]
pub fn add(&mut self, job: Job<'a>) -> Uuid {
let job_id = job.job_id;
self.jobs.push(job);
job_id
}
/// Remove a job from the `JobScheduler`
///
/// ```rust,ignore
/// let mut sched = JobScheduler::new();
/// let job_id = sched.add(Job::new("1/10 * * * * *".parse().unwrap(), || {
/// println!("I get executed every 10 seconds!");
/// }));
/// sched.remove(job_id);
/// ```
#[inline]
pub fn remove(&mut self, job_id: Uuid) -> bool {
let mut found_index = None;
for (i, job) in self.jobs.iter().enumerate() {
if job.job_id == job_id {
found_index = Some(i);
break;
}
}
if let Some(index) = found_index {
self.jobs.remove(index);
}
found_index.is_some()
}
/// The `tick` method increments time for the JobScheduler and executes
/// any pending jobs. It is recommended to sleep for at least 500
/// milliseconds between invocations of this method.
///
/// ```rust,ignore
/// loop {
/// sched.tick();
/// std::thread::sleep(Duration::from_millis(500));
/// }
/// ```
#[inline]
pub fn tick(&mut self) {
for job in &mut self.jobs {
job.tick();
}
}
/// The `time_till_next_job` method returns the duration till the next job
/// is supposed to run. This can be used to sleep until then without waking
/// up at a fixed interval.AsMut
///
/// ```rust, ignore
/// loop {
/// sched.tick();
/// std::thread::sleep(sched.time_till_next_job());
/// }
/// ```
#[inline]
pub fn time_till_next_job(&self) -> core::time::Duration {
if self.jobs.is_empty() {
// Take a guess if there are no jobs.
return core::time::Duration::from_millis(500);
}
let mut duration = Duration::zero();
let now = Utc::now();
for job in &self.jobs {
for event in job.schedule.upcoming(offset::Utc).take(1) {
let d = event - now;
if duration.is_zero() || d < duration {
duration = d;
}
}
}
duration.to_std().unwrap()
}
}