mvniekerk / tokio-cron-scheduler

Schedule tasks on Tokio using cron-like annotation
Apache License 2.0
529 stars 59 forks source link

Custom code use Local time #44

Closed daiguadaidai closed 9 months ago

daiguadaidai commented 1 year ago
#[cfg(test)]
mod tests {
    use chrono::Local;
    use cron::Schedule;
    use std::str::FromStr;
    use std::thread::sleep;
    use std::time;
    use tokio::sync::mpsc;

    const TIME_FORMAT: &str = "%Y-%m-%d %H:%M:%S";

    #[tokio::test]
    async fn tokio_mpsc_cron_01() {
        let (tx1, mut rx1) = mpsc::channel::<bool>(1);

        tokio::spawn(async move {
            loop {
                let expression = "*/10 * * * * *";
                let schedule = Schedule::from_str(expression).unwrap();

                loop {
                    for datetime in schedule.upcoming(Local).take(1) {
                        let now = chrono::Local::now();
                        // now datetime
                        // calc diff millis
                        let millis = datetime.timestamp_millis() - now.timestamp_millis();
                        // If the timing time is less than the current time, exit this operation and proceed to the next time
                        println!(
                            "now: {:?}, task time: {:?}, diff millis: {}",
                            chrono::Local::now().format(TIME_FORMAT).to_string(),
                            datetime.format(TIME_FORMAT).to_string(),
                            millis
                        );
                        if millis < 0 {
                            break;
                        }

                        // Sleep reaches the time required to perform tasks
                        let _ = tokio::time::sleep(std::time::Duration::from_millis(millis as u64))
                            .await;
                        println!(
                            "send msg: {:?}",
                            chrono::Local::now().format(TIME_FORMAT).to_string()
                        );
                        let _ = tx1.send(true).await;
                    }
                }
            }
        });

        loop {
            tokio::select! {
                Some(val) = rx1.recv() => {
                    let _ = tokio::spawn(async move {

                        let _ = start_cron(val).await;
                    });
                }
            }
        }
    }

    async fn start_cron(val: bool) {
        println!(
            "start cron job task: {:?}, {:?}",
            val,
            chrono::Local::now().format(TIME_FORMAT).to_string()
        );
        let _ = tokio::time::sleep(std::time::Duration::from_secs(8)).await;
    }
}
mvniekerk commented 9 months ago

Please check v0.10 if this works better for you wrt Timezones?