#Rust Reqwest fire and forget
12 messages · Page 1 of 1 (latest)
It doesnot work actually I tested it out.
LLM suggested this, but still does not work
#[tokio::main]
async fn main() {
tokio::spawn(async {
let _ = reqwest::get("http://example.com").await;
});
println!("Request sent, moving on...");
// Keep the runtime alive long enough
tokio::time::sleep(std::time::Duration::from_secs(1)).await;
}
Tokio is a runtime for writing reliable asynchronous applications with Rust. It provides async I/O, networking, scheduling, timers, and more.
Might be of interest but if you want to fire and forget why do this in the first place. If you end up waiting for the task to finish anyway is it much different than just an await?
Depending on what you are trying to do https://docs.rs/tokio/latest/tokio/task/struct.JoinSet.html might be useful as well.
A collection of tasks spawned on a Tokio runtime.
tokio::spawn returns a handle to the task which you can await. Instead of the sleep just store the handle in a variable and call await on it instead of sleeping.
A browser interface to the Rust compiler to experiment with the language
For example this does the same but instead of waiting one second which doesnt guarantee the task will be completed, it just stores the handle waits until the task is completed before exiting.
That said I don't recommend using LLM's as they often cause more confusion than help when learning. tokio's documentation is pretty good so you are better off reading that instead.
Yeah I wouldn't trust llms with async rust tbh 😅
I setup something like this and I get this flow, I would like to not care about the second request at all.
#[tokio::main]
async fn main() -> Result<()> {
let _ = fire_and_forget().await;
println!("Running other Task");
println!("Final Task");
Ok(())
}
async fn fire_and_forget() -> Result<()> {
println!("starting request 1");
let _ = reqwest::get("http://localhost:8000").await;
println!("ending request 1");
println!("Starting request 2");
let h = tokio::spawn(async {
let _ = reqwest::get("http://localhost:8000").await;
println!("ending request 2");
});
let _ = h.await;
Ok(())
}
The real world usecase is that Im trying to run a middleware, where I would like to call to extend session of the user (which is not critical that it needs to work). I would like it to be like the beacon api from js