[][src]Struct tokio::runtime::Runtime

pub struct Runtime { /* fields omitted */ }

The Tokio runtime.

The runtime provides an I/O driver, task scheduler, timer, and blocking pool, necessary for running asynchronous tasks.

Instances of Runtime can be created using new or Builder. However, most users will use the #[tokio::main] annotation on their entry point instead.

See module level documentation for more details.

Shutdown

Shutting down the runtime is done by dropping the value. The current thread will block until the shut down operation has completed.

Once the reactor has dropped, any outstanding I/O resources bound to that reactor will no longer function. Calling any method on them will result in an error.

Implementations

impl Runtime[src]

pub fn new() -> Result<Runtime>[src]

Create a new runtime instance with default configuration values.

This results in a scheduler, I/O driver, and time driver being initialized. The type of scheduler used depends on what feature flags are enabled: if the rt-threaded feature is enabled, the threaded scheduler is used, while if only the rt-core feature is enabled, the basic scheduler is used instead.

If the threaded scheduler is selected, it will not spawn any worker threads until it needs to, i.e. tasks are scheduled to run.

Most applications will not need to call this function directly. Instead, they will use the #[tokio::main] attribute. When 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 spawn<F>(&self, future: F) -> JoinHandle<F::Output>

Notable traits for JoinHandle<T>

impl<T> Future for JoinHandle<T> type Output = Result<T, JoinError>;
where
    F: Future + Send + 'static,
    F::Output: Send + 'static, 
[src]

Spawn 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.

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");
});

Panics

This function will not panic unless task execution is disabled on the executor. This can only happen if the runtime was built using Builder without picking either basic_scheduler or threaded_scheduler.

pub fn block_on<F: Future>(&mut self, future: F) -> F::Output[src]

Run a future to completion on the Tokio runtime. This is the runtime's entry point.

This runs the given future on the runtime, 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.

&mut is required as calling block_on may result in advancing the state of the runtime. The details depend on how the runtime is configured. runtime::Handle::block_on provides a version that takes &self.

This method may not be called from an asynchronous context.

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 mut rt = Runtime::new().unwrap();

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

pub fn enter<F, R>(&self, f: F) -> R where
    F: FnOnce() -> R, 
[src]

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

This function is also available as Handle::enter.

Example

use tokio::runtime::Runtime;

fn function_that_spawns(msg: String) {
    // 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.
    rt.enter(|| function_that_spawns(s));
}

pub fn handle(&self) -> &Handle[src]

Return 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.

Examples

use tokio::runtime::Runtime;

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

let handle = rt.handle();

handle.spawn(async { println!("hello"); });

pub fn shutdown_timeout(self, duration: Duration)[src]

Shutdown the runtime, waiting for at most duration for all spawned task to shutdown.

Usually, dropping a Runtime handle is sufficient as tasks are able to shutdown in a timely fashion. However, dropping a Runtime will wait indefinitely for all tasks to terminate, and there are cases where a long blocking task has been spawned, which can block dropping Runtime.

In this case, calling shutdown_timeout with an explicit wait timeout can work. The shutdown_timeout will signal all tasks to shutdown and will wait for at most duration for all spawned tasks to terminate. If timeout elapses before all tasks are dropped, the function returns and outstanding tasks are potentially leaked.

Examples

use tokio::runtime::Runtime;
use tokio::task;

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

fn main() {
   let mut 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)[src]

Shutdown the runtime, without waiting for any spawned tasks to shutdown.

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.

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

use tokio::runtime::Runtime;

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

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

Trait Implementations

impl Debug for Runtime[src]

Auto Trait Implementations

impl !RefUnwindSafe for Runtime

impl Send for Runtime

impl Sync for Runtime

impl Unpin for Runtime

impl !UnwindSafe for Runtime

Blanket Implementations

impl<T> Any for T where
    T: 'static + ?Sized
[src]

impl<T> Borrow<T> for T where
    T: ?Sized
[src]

impl<T> BorrowMut<T> for T where
    T: ?Sized
[src]

impl<T> From<T> for T[src]

impl<T, U> Into<U> for T where
    U: From<T>, 
[src]

impl<T, U> TryFrom<U> for T where
    U: Into<T>, 
[src]

type Error = Infallible

The type returned in the event of a conversion error.

impl<T, U> TryInto<U> for T where
    U: TryFrom<T>, 
[src]

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.