✨ cron
This commit is contained in:
parent
18c663fcdb
commit
46cb21dc2a
8 changed files with 575 additions and 6 deletions
76
src/lib.rs
76
src/lib.rs
|
@ -1,5 +1,11 @@
|
|||
use std::{sync::mpsc, thread, time::Instant};
|
||||
#![feature(fn_traits)]
|
||||
use std::{
|
||||
sync::mpsc,
|
||||
thread,
|
||||
time::{Duration, Instant},
|
||||
};
|
||||
|
||||
pub mod cron;
|
||||
mod defer;
|
||||
pub mod iterated;
|
||||
pub mod job;
|
||||
|
@ -69,3 +75,71 @@ pub fn retry<O, F: Fn() -> Option<O>>(f: F) -> O {
|
|||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Run a background task.
|
||||
///
|
||||
/// This spawns a seperate thread for a background process.
|
||||
/// The background task is guaranteed to finish within its defined scope.
|
||||
/// If the end of the scope is reached while the thread is still running it will block.
|
||||
///
|
||||
/// # Example
|
||||
/// ```ignore
|
||||
/// use comrade::background;
|
||||
///
|
||||
/// fn do_work() {
|
||||
/// println!("doing work...");
|
||||
///
|
||||
/// // spawn background thread
|
||||
/// background!(|| {
|
||||
/// println!("doing something in the background");
|
||||
/// std::thread::sleep(std::time::Duration::from_secs(3));
|
||||
/// });
|
||||
///
|
||||
/// println!("doing something else...");
|
||||
///
|
||||
/// // end of scope
|
||||
/// // the code will block until all background processes defined here are done.
|
||||
/// }
|
||||
///
|
||||
/// fn main() {
|
||||
/// do_work();
|
||||
/// println!("finished with work");
|
||||
/// }
|
||||
/// ```
|
||||
#[macro_export]
|
||||
macro_rules! background {
|
||||
($f:expr) => {
|
||||
let handle = std::thread::spawn(move || $f());
|
||||
comrade::defer!(|| {
|
||||
handle.join().unwrap();
|
||||
});
|
||||
};
|
||||
}
|
||||
|
||||
/// Start running a function after `duration`.
|
||||
pub fn delay<F: Fn() + Send + 'static>(duration: std::time::Duration, f: F) {
|
||||
let _ = std::thread::spawn(move || {
|
||||
log::info!("Will start running in {duration:?}");
|
||||
std::thread::sleep(duration);
|
||||
f();
|
||||
});
|
||||
}
|
||||
|
||||
/// Run `f(&T) -> X` for every item in `items`
|
||||
pub fn parallel<T: Send + Sync + 'static, F, X: Send + 'static>(items: Vec<T>, f: F) -> Vec<X>
|
||||
where
|
||||
F: Fn(&T) -> X + Send + Sync + Copy + 'static,
|
||||
{
|
||||
let threads: Vec<_> = items
|
||||
.into_iter()
|
||||
.map(|x| std::thread::spawn(move || f(&x)))
|
||||
.collect();
|
||||
|
||||
threads.into_iter().map(|x| x.join().unwrap()).collect()
|
||||
}
|
||||
|
||||
pub fn datetime_in(d: Duration) -> chrono::DateTime<chrono::Utc> {
|
||||
chrono::Utc::now()
|
||||
.checked_add_signed(chrono::TimeDelta::from_std(d).unwrap())
|
||||
.unwrap()
|
||||
}
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue