Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Actix web support #22

Open
shiftrtech opened this issue Oct 29, 2020 · 1 comment
Open

Actix web support #22

shiftrtech opened this issue Oct 29, 2020 · 1 comment

Comments

@shiftrtech
Copy link

Hi, there is a way to work with actix-web?

@Valentine-Mario
Copy link

Valentine-Mario commented Dec 5, 2020

When using Actix web, I had to make use of Actix Actors as this crate interferes with the Actix run time

use actix::prelude::*;
use chrono::Local;
use cron::Schedule;
use std::{str::FromStr, time::Duration};


// Define actor
pub struct Scheduler;

// Provide Actor implementation for our actor
impl Actor for Scheduler {
    type Context = Context<Self>;

    fn started(&mut self, ctx: &mut Context<Self>) {
        println!("Actor is alive");

        ctx.run_later(duration_until_next(), move |this, ctx| {
            this.schedule_task(ctx)
        });
    }

    fn stopped(&mut self, _ctx: &mut Context<Self>) {
        println!("Actor is stopped");
    }
}

impl Scheduler {
    fn schedule_task(&self, ctx: &mut Context<Self>) {
        // executes every 1 minute based on cron schedule
        println!("schedule_task event - {:?}", Local::now());

        ctx.run_later(duration_until_next(), move |this, ctx| {
            this.schedule_task(ctx)
        });
    }
}

pub fn duration_until_next() -> Duration {
    let cron_expression = "0 * * * * * *"; //every minute
    let cron_schedule = Schedule::from_str(cron_expression).unwrap();
    let now = Local::now();
    let next = cron_schedule.upcoming(Local).next().unwrap();
    let duration_until = next.signed_duration_since(now);
    Duration::from_millis(duration_until.num_milliseconds() as u64)
}

Then in your main.rs fn :

Scheduler.start();
Hope this helps

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants