Struct Runtime
struct Runtime { ... }
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, or calling
shutdown_background or shutdown_timeout.
Tasks spawned through Runtime::spawn keep running until they yield.
Then they are dropped. They are not guaranteed to run to completion, but
might do so if they do not yield until completion.
Blocking functions spawned through Runtime::spawn_blocking keep running
until they return.
The thread initiating the shutdown blocks until all spawned work has been
stopped. This can take an indefinite amount of time. The Drop
implementation waits forever for this.
The shutdown_background and shutdown_timeout methods can be used if
waiting forever is undesired. When the timeout is reached, spawned work that
did not stop in time and threads running it are leaked. The work continues
to run until one of the stopping conditions is fulfilled, but the thread
initiating the shutdown is unblocked.
Once the runtime has been dropped, any outstanding I/O resources bound to it will no longer function. Calling any method on them will result in an error.
Sharing
There are several ways to establish shared access to a Tokio runtime:
Using an Arc<Runtime> or Handle allows you to do various
things with the runtime such as spawning new tasks or entering the runtime
context. Both types can be cloned to create a new handle that allows access
to the same runtime. By passing clones into different tasks or threads, you
will be able to access the runtime from those tasks or threads.
The difference between Arc<Runtime> and Handle is that
an Arc<Runtime> will prevent the runtime from shutting down,
whereas a Handle does not prevent that. This is because shutdown of the
runtime happens when the destructor of the Runtime object runs.
Calls to shutdown_background and shutdown_timeout require exclusive
ownership of the Runtime type. When using an Arc<Runtime>,
this can be achieved via Arc::try_unwrap when only one strong count
reference is left over.
The runtime context is entered using the Runtime::enter or
Handle::enter methods, which use a thread-local variable to store the
current runtime. Whenever you are inside the runtime context, methods such
as tokio::spawn will use the runtime whose context you are inside.
Implementations
impl Runtime
fn new() -> Result<Runtime>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
Runtimewith default configuration values.use Runtime; let rt = new .unwrap; // Use the runtime...fn handle(self: &Self) -> &HandleReturns 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
Handleto other threads.Calling
Handle::block_onon a handle to acurrent_threadruntime is error-prone. Refer to the documentation ofHandle::block_onfor more.Examples
use Runtime; let rt = new .unwrap; let handle = rt.handle; // Use the handle...fn spawn<F>(self: &Self, future: F) -> JoinHandle<<F as >::Output> where F: Future + Send + 'static, <F as >::Output: Send + 'staticSpawns 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
spawnis called, even if you don't await the returnedJoinHandle.See module level documentation for more details.
Examples
use Runtime; #fn spawn_blocking<F, R>(self: &Self, func: F) -> JoinHandle<R> where F: FnOnce() -> R + Send + 'static, R: Send + 'staticRuns the provided function on an executor dedicated to blocking operations.
Examples
use Runtime; #fn block_on<F: Future>(self: &Self, future: F) -> <F as >::OutputRuns 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_onreturns.Current thread scheduler
When the current thread scheduler is enabled
block_oncan 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 firstblock_oncompletes, other threads will be able to "steal" the driver to allow continued execution of their futures.Any spawned tasks will be suspended after
block_onreturns. Callingblock_onagain 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"); });fn enter(self: &Self) -> EnterGuard<'_>Enters the runtime context.
This allows you to construct types that must have an executor available on creation such as
SleeporTcpStream. It will also allow you to call methods such astokio::spawn.Example
use Runtime; use JoinHandle;fn shutdown_timeout(self: Self, duration: Duration)Shuts down the runtime, waiting for at most
durationfor all spawned work to stop.See the struct level documentation for more details.
Examples
use Runtime; use task; use thread; use Duration;fn shutdown_background(self: 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 Runtime;fn metrics(self: &Self) -> RuntimeMetricsReturns a view that lets you get information about how the runtime is performing.
impl Debug for Runtime
fn fmt(self: &Self, f: &mut Formatter<'_>) -> Result
impl Drop for Runtime
fn drop(self: &mut Self)
impl Freeze for Runtime
impl RefUnwindSafe for Runtime
impl Send for Runtime
impl Sync for Runtime
impl Unpin for Runtime
impl UnsafeUnpin for Runtime
impl UnwindSafe for Runtime
impl<T> Any for Runtime
fn type_id(self: &Self) -> TypeId
impl<T> Borrow for Runtime
fn borrow(self: &Self) -> &T
impl<T> BorrowMut for Runtime
fn borrow_mut(self: &mut Self) -> &mut T
impl<T> From for Runtime
fn from(t: T) -> TReturns the argument unchanged.
impl<T, U> Into for Runtime
fn into(self: Self) -> UCalls
U::from(self).That is, this conversion is whatever the implementation of
[From]<T> for Uchooses to do.
impl<T, U> TryFrom for Runtime
fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>
impl<T, U> TryInto for Runtime
fn try_into(self: Self) -> Result<U, <U as TryFrom<T>>::Error>