Update an Actix State periodically


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?


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 {
1 Like

Thanks a lot @alice!!

It's ok to have a system like this?

async fn main() -> std::io::Result<()> {
    let rt = Runtime::new().unwrap();
    //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 {
            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


This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.