schedule-rs icon indicating copy to clipboard operation
schedule-rs copied to clipboard

One scheduled function stops others from running

Open glennpierce opened this issue 8 years ago • 2 comments

I have an example below which schedules three functions / closures to run at the same time. However, they don't seem to run async. Is this by design ? Are you expected to run within a thread.

Thanks

extern crate schedule; extern crate chrono;

use std::{thread, time}; use chrono::*;

fn hello_world_5() { println!("{}: Hello World (every 5 seconds)!", Utc::now()); thread::sleep(time::Duration::from_millis(10000)); println!("Done hello_world_5"); }

#[test] fn schedule_hello() { // Create new, empty agenda let mut a = schedule::Agenda::new();

// Add a job from a closure, scheduled to run every 2 seconds
a.add(|| {
             println!("{}: Hello World (every 2 seconds)!", Utc::now());
             thread::sleep(time::Duration::from_millis(5000));
             println!("Done hello_world_2");
         })
    .schedule("0 * * * * *")
    .unwrap();

// Add a job from a function and give it a name
a.add(hello_world_5).with_name("hello-world");

a.add(|| {
             println!("{}: Hello World (every 3 seconds)!", Utc::now());
         })
    .schedule("0 * * * * *")
    .unwrap();

// Schedule that job to run every 5 seconds
a.get("hello-world")
    .unwrap()
    .schedule("0 * * * * *")
    .unwrap();

loop {
    // Execute pending jobs
    a.run_pending();

    // Sleep for 500ms
    thread::sleep(time::Duration::from_millis(500));
}

}

glennpierce avatar Oct 25 '17 14:10 glennpierce

In the end I forked and added the function below to get the effect I wanted.

pub fn run_pending_async(&mut self) {
        crossbeam::scope(|scope| {
            for job in &mut self.jobs {

                if job.is_pending() {
                    scope.spawn(move || {
                        job.run();
                    });
                }
            }
        });
    }

glennpierce avatar Oct 26 '17 08:10 glennpierce

@glennpierce This is by design at the moment mostly because it's very simple. I'm glad you got it working.

I'm planning on circling back to this at some point in the near future and generalizing the agenda over an executor. I want a user to be able to execute each job in an event loop or a thread pool or something custom.

mehcode avatar Oct 26 '17 08:10 mehcode