嘿,我有一个异步进程,它是资源耗尽的。我必须将它暴露给一个API,如何在后台和队列中一个接一个地处理作业。我使用了tokio::spawn
,但所有派生的任务最终都同时运行。
我将在下面附上一个简单的可复制代码以供参考。
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);
}
字符串
1条答案
按热度按时间lxkprmvk1#
只需
spawn
一个任务来进行处理并使用通道与之通信:字符串