Function rocket::execute

source ·
pub fn execute<R, F>(future: F) -> R
where F: Future<Output = R> + Send,
Expand description

Executes a future to completion on a new tokio-based Rocket async runtime.

The runtime is terminated on shutdown, and the future’s resolved value is returned.

§Considerations

This function is a low-level mechanism intended to be used to execute the future returned by Rocket::launch() in a self-contained async runtime designed for Rocket. It runs futures in exactly the same manner as #[launch] and #[main] do and is thus never the preferred mechanism for running a Rocket application. Always prefer to use the #[launch] or #[main] attributes. For example #[main] can be used even when Rocket is just a small part of a bigger application:

#[rocket::main]
async fn main() {
    let rocket = rocket::build();
    if should_start_server_in_foreground {
        rocket::build().launch().await;
    } else if should_start_server_in_background {
        rocket::tokio::spawn(rocket.launch());
    } else {
        // do something else
    }
}

See Rocket for more on using these attributes.

§Example

Build an instance of Rocket, launch it, and wait for shutdown:

use rocket::fairing::AdHoc;

let rocket = rocket::build()
    .attach(AdHoc::on_liftoff("Liftoff Printer", |_| Box::pin(async move {
        println!("Stalling liftoff for a second...");
        rocket::tokio::time::sleep(std::time::Duration::from_secs(1)).await;
        println!("And we're off!");
    })));

rocket::execute(rocket.launch());

Launch a pre-built instance of Rocket and wait for it to shutdown:

use rocket::{Rocket, Ignite, Phase, Error};

fn launch<P: Phase>(rocket: Rocket<P>) -> Result<Rocket<Ignite>, Error> {
    rocket::execute(rocket.launch())
}

Do async work to build an instance of Rocket, launch, and wait for shutdown:

use rocket::fairing::AdHoc;

// This line can also be inside of the `async` block.
let rocket = rocket::build();

rocket::execute(async move {
    let rocket = rocket.ignite().await?;
    let config = rocket.config();
    rocket.launch().await
});