Type Alias Default

pub type Default = Runtime;
Expand description

A tokio executor.

Aliased Type§

struct Default { /* private fields */ }

Implementations

§

impl Runtime

pub fn new() -> Result<Runtime, Error>

Creates a new runtime instance with default configuration values.

This results in the multi threaded scheduler, I/O driver, and time driver being initialized.

Most applications will not need to call this function directly. Instead, they will use the #[tokio::main] attribute. When a more complex configuration is necessary, the runtime builder may be used.

See module level documentation for more details.

§Examples

Creating a new Runtime with default configuration values.

use tokio::runtime::Runtime;

let rt = Runtime::new()
    .unwrap();

// Use the runtime...

pub fn handle(&self) -> &Handle

Returns a handle to the runtime’s spawner.

The returned handle can be used to spawn tasks that run on this runtime, and can be cloned to allow moving the Handle to other threads.

Calling [Handle::block_on] on a handle to a current_thread runtime is error-prone. Refer to the documentation of [Handle::block_on] for more.

§Examples
use tokio::runtime::Runtime;

let rt = Runtime::new()
    .unwrap();

let handle = rt.handle();

// Use the handle...

pub fn spawn<F>(&self, future: F) -> JoinHandle<<F as Future>::Output>
where F: Future + Send + 'static, <F as Future>::Output: Send + 'static,

Spawns a future onto the Tokio runtime.

This spawns the given future onto the runtime’s executor, usually a thread pool. The thread pool is then responsible for polling the future until it completes.

The provided future will start running in the background immediately when spawn is called, even if you don’t await the returned JoinHandle.

See module level documentation for more details.

§Examples
use tokio::runtime::Runtime;

// Create the runtime
let rt = Runtime::new().unwrap();

// Spawn a future onto the runtime
rt.spawn(async {
    println!("now running on a worker thread");
});

pub fn spawn_blocking<F, R>(&self, func: F) -> JoinHandle<R>
where F: FnOnce() -> R + Send + 'static, R: Send + 'static,

Runs the provided function on an executor dedicated to blocking operations.

§Examples
use tokio::runtime::Runtime;

// Create the runtime
let rt = Runtime::new().unwrap();

// Spawn a blocking function onto the runtime
rt.spawn_blocking(|| {
    println!("now running on a worker thread");
});

pub fn block_on<F>(&self, future: F) -> <F as Future>::Output
where F: Future,

Runs a future to completion on the Tokio runtime. This is the runtime’s entry point.

This runs the given future on the current thread, blocking until it is complete, and yielding its resolved result. Any tasks or timers which the future spawns internally will be executed on the runtime.

§Non-worker future

Note that the future required by this function does not run as a worker. The expectation is that other tasks are spawned by the future here. Awaiting on other futures from the future provided here will not perform as fast as those spawned as workers.

§Multi thread scheduler

When the multi thread scheduler is used this will allow futures to run within the io driver and timer context of the overall runtime.

Any spawned tasks will continue running after block_on returns.

§Current thread scheduler

When the current thread scheduler is enabled block_on can be called concurrently from multiple threads. The first call will take ownership of the io and timer drivers. This means other threads which do not own the drivers will hook into that one. When the first block_on completes, other threads will be able to “steal” the driver to allow continued execution of their futures.

Any spawned tasks will be suspended after block_on returns. Calling block_on again will resume previously spawned tasks.

§Panics

This function panics if the provided future panics, or if called within an asynchronous execution context.

§Examples
use tokio::runtime::Runtime;

// Create the runtime
let rt  = Runtime::new().unwrap();

// Execute the future, blocking the current thread until completion
rt.block_on(async {
    println!("hello");
});

pub fn enter(&self) -> EnterGuard<'_>

Enters the runtime context.

This allows you to construct types that must have an executor available on creation such as Sleep or TcpStream. It will also allow you to call methods such as tokio::spawn.

§Example
use tokio::runtime::Runtime;
use tokio::task::JoinHandle;

fn function_that_spawns(msg: String) -> JoinHandle<()> {
    // Had we not used `rt.enter` below, this would panic.
    tokio::spawn(async move {
        println!("{}", msg);
    })
}

fn main() {
    let rt = Runtime::new().unwrap();

    let s = "Hello World!".to_string();

    // By entering the context, we tie `tokio::spawn` to this executor.
    let _guard = rt.enter();
    let handle = function_that_spawns(s);

    // Wait for the task before we end the test.
    rt.block_on(handle).unwrap();
}

pub fn shutdown_timeout(self, duration: Duration)

Shuts down the runtime, waiting for at most duration for all spawned work to stop.

See the struct level documentation for more details.

§Examples
use tokio::runtime::Runtime;
use tokio::task;

use std::thread;
use std::time::Duration;

fn main() {
   let runtime = Runtime::new().unwrap();

   runtime.block_on(async move {
       task::spawn_blocking(move || {
           thread::sleep(Duration::from_secs(10_000));
       });
   });

   runtime.shutdown_timeout(Duration::from_millis(100));
}

pub fn shutdown_background(self)

Shuts down the runtime, without waiting for any spawned work to stop.

This can be useful if you want to drop a runtime from within another runtime. Normally, dropping a runtime will block indefinitely for spawned blocking tasks to complete, which would normally not be permitted within an asynchronous context. By calling shutdown_background(), you can drop the runtime from such a context.

Note however, that because we do not wait for any blocking tasks to complete, this may result in a resource leak (in that any blocking tasks are still running until they return.

See the struct level documentation for more details.

This function is equivalent to calling shutdown_timeout(Duration::from_nanos(0)).

use tokio::runtime::Runtime;

fn main() {
   let runtime = Runtime::new().unwrap();

   runtime.block_on(async move {
       let inner_runtime = Runtime::new().unwrap();
       // ...
       inner_runtime.shutdown_background();
   });
}

pub fn metrics(&self) -> RuntimeMetrics

Returns a view that lets you get information about how the runtime is performing.

Trait Implementations

§

impl Debug for Runtime

§

fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more
§

impl Drop for Runtime

§

fn drop(&mut self)

Executes the destructor for this type. Read more
§

impl Executor for Runtime

§

fn new() -> Result<Runtime, Error>

Creates a new Executor.
§

fn spawn(&self, future: impl Future<Output = ()> + Send + 'static)

Spawns a future in the Executor.
§

fn enter<R>(&self, f: impl FnOnce() -> R) -> R

Runs the given closure inside the Executor. Read more
§

fn block_on<T>(&self, future: impl Future<Output = T>) -> T

Runs a future to completion in the current thread within the Executor.
§

impl RefUnwindSafe for Runtime

§

impl UnwindSafe for Runtime