Hey I have a async process which is resource exhaustive. And I have to expose it to an API how to process jobs in background and in queue one after one. I used tokio::spawn
but all spawned tasks are ending up running simultaneously.
I will attach a simple reproducible code below for reference.
use axum::{extract::Path, routing::get, Router};
use tokio::time::Duration;
extern crate diesel;
extern crate tracing;
#[tokio::main]
async fn main() {
tracing_subscriber::fmt::init();
let app = Router::new().route("/sleep/:id", get(sleep_and_print));
let addr = std::net::SocketAddr::from(([0, 0, 0, 0], 3000));
tracing::info!("Listening on {}", addr);
axum::Server::bind(&addr)
.serve(app.into_make_service())
.await
.unwrap();
}
async fn sleep_and_print(Path(timer): Path<i32>) -> String {
tokio::spawn(async move {
start_timer_send_json(timer).await;
});
format!("{{\"timer\": {}}}", timer)
}
async fn start_timer_send_json(timer: i32) {
println!("Start timer {}.", timer);
tokio::time::sleep(Duration::from_secs(300)).await;
println!("Timer {} done.", timer);
}