The cron-job
library lets you create cronjobs. This is basically
an implementation of the cron
library.
You can schedule your own functions as jobs.
``` Functions extern crate cronjob; use cronjob::CronJob;
fn main() { // Create CronJob let mut cron = CronJob::new(); // Add the function cron.newjob("* * * * * *", runon_cron); // Start job cron.start(); }
// The function to be executed. fn runoncron() { println!("Executed function"); } ```
Multiple functions with different cron expression can also be added.
``` Multiple functions extern crate cronjob; use cronjob::CronJob;
fn main() { // Create CronJob let mut cron = CronJob::new(); // Add the function to be run every second cron.newjob("* * * * * *", runeverysecond); // Add the function to be run every 5 seconds cron.newjob("*/5 * * * * *", runeveryfive_minutes); // Start jobs cron.start(); }
// The function to be executed every second. fn runeverysecond() { println!("1 second"); }
// The function to be executed every 5 minutes. fn runeveryfive_seconds() { println!("5 minutes"); } ```
Since the function used as job cannot have any parameters, the
Job
trait is available to be implemented to structs. This way
if any parameter needs to be passed to the function, can be
passed as the struct property.
``` Job extern crate cronjob; use cronjob::CronJob;
fn main() { // Create HelloJob let helloJob = HelloJob{ name: "John" }; // Create CronJob let mut cron = CronJob::new(); // Say hello every second cron.new_job("* * * * * *", helloJob); // Start jobs cron.start(); }
// The job to be executed struct HelloJob { name: String }
impl Job for HelloJob { fn run(&self) { println!("Hello, {}!", self.name); } } ```
Functions and job can be mixed together.
``` Function and job extern crate cronjob; use cronjob::CronJob;
fn main() { // Create HelloJob let helloJob = HelloJob{ name: "John" }; // Create CronJob let mut cron = CronJob::new(); // Run function every second cron.newjob("* * * * * *", runeverysecond); // Say hello every second cron.newjob("* * * * * *", helloJob); // Start jobs cron.start(); } // The function to be executed every second. fn runeverysecond() { println!("1 second"); }
// The job to be executed struct HelloJob { name: String }
// Very important, implement the Job trait and its functions. impl Job for HelloJob { fn run(&self) { println!("Hello, {}!", self.name); } } ```