Running background jobs in an Actix wep application

256 Views Asked by At

I have a small Rust wep application created with Actix. While running the Actix web server, I want the application to continuously run a loop in the background that runs a task every X seconds. I'm pretty new to Rust and I have been doing a lot of trial and error trying to do this.

I have tried different approaches and I have gotten the below code example to work.

#[actix_web::main]
pub async fn start_server() {
    actix_web::rt::spawn(async {
        loop {
            println!("Starting a task that takes 5 seconds.");
            actix_rt::time::sleep(Duration::from_millis(5000)).await;

            println!("Waiting 30 seconds before the task will run again.");
            actix_rt::time::sleep(Duration::from_millis(30000)).await;
        }
    });

    HttpServer::new(|| App::new().service(health))
        .bind(("127.0.0.1", 8080))
        .unwrap()
        .run()
        .await
        .unwrap();
}

Is there any caveats doing it this way or maybe there's a completely different way of achieving this with better results?

-Post was edited after @kmdreko fixed an issue.

0

There are 0 best solutions below