Background task is blocking #2124
-
Running #[launch]
async fn rocket() -> _ {
let file = fs::read_to_string("stats.json").expect("Unable to read file");
let stats: api::Stats = serde_json::from_str(&file).expect("Could not parse json");
dotenv::dotenv().ok();
rocket::build()
.attach(Template::fairing())
.attach(info::stage())
.attach(api::stage())
.mount("/", routes![index])
.mount("/static", FileServer::from(relative!("static")))
.manage(stats)
.attach(rocket::fairing::AdHoc::on_liftoff(
"Background task",
|rocket| {
Box::pin(async move {
let mut interval = rocket::tokio::time::interval(Duration::from_secs(600));
interval.tick().await;
loop {
interval.tick().await;
if let Some(state) = rocket.state::<Stats>() {
let json = serde_json::to_string(state).unwrap();
println!("{}", json);
}
}
})
},
))
} When I run this, the loop runs but rocket seems to get blocked and just never starts, when I comment out the |
Beta Was this translation helpful? Give feedback.
Answered by
SergioBenitez
Mar 17, 2022
Replies: 1 comment 2 replies
-
That's exactly what we would expect. From the docs:
Your fairing never terminates. If you want to run your loop in a background task, you need to task::spawn a new task. |
Beta Was this translation helpful? Give feedback.
2 replies
Answer selected by
Leastrio
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
That's exactly what we would expect. From the docs:
Your fairing never terminates. If you want to run your loop in a background task, you need to task::spawn a new task.