Update an Actix State periodically

Hi!

I have a simple actix web service with some endpoints and a shared state. I would like to each ten seconds run a function to update the state. Is there a way to do this with actix api or must I use a lib like https://github.com/lholden/job_scheduler?

Thx

Actix internally uses Tokio for its tasks, so you can just spawn an ordinary Tokio task.

tokio::spawn(async move {
    let interval = tokio::time::interval(Duration::from_secs(10));
    loop {
        interval.tick().await;
        do_the_thing();
    }
});
1 Like

Thanks a lot @alice!!

It's ok to have a system like this?

#[actix_web::main]
async fn main() -> std::io::Result<()> {
    let rt = Runtime::new().unwrap();
    jobs::launch(&rt);
    //The server start after 
}

fn create_periodically_task(rt: &Runtime, duration_in_secs: u64) {
    rt.spawn(async move {
        let mut interval = interval(Duration::from_secs(duration_in_secs));
        loop {
            interval.tick().await;
            println!("This task run every {} seconds ", duration_in_secs);
        }
    });
}

struct Task {
    every: u64
}

pub fn launch(rt: &Runtime) {
    let mut tasks = Vec::new();
    // Add a task to run every 10 seconds
    tasks.push(Task { every: 10 });
    // Add a task to run every 30 seconds
    tasks.push(Task { every: 30 });
    // Add a task to run every minutes
    tasks.push(Task { every: 60 });

    for task in tasks {
       create_periodically_task(rt, task.every);
    }
}

You shouldn't create another runtime. The #[actix_web::main] macro already creates one for you (unless I've misunderstood something). Just call the tokio::spawn function directly.

If I use tokio::spawn directly without extra runtime, the app panics with the error message: must be called from the context of Tokio runtime

Make sure the versions of Tokio match up. Actix probably still uses Tokio 0.2.

Ok I will check the version thanks!

It's bad to have another runtime?

Well it's inefficient at least.

I downgraded the Tokio version to 0.2.22 and it works!
Thanks again @alice

2 Likes