Skip to main content

ntex_rt/
rt_default.rs

1use std::{fmt, future::Future, time::Instant};
2
3pub use crate::{handle::JoinHandle, rt::Handle, rt::Runtime};
4
5#[derive(Debug, Copy, Clone)]
6pub struct JoinError;
7
8impl fmt::Display for JoinError {
9    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
10        write!(f, "JoinError")
11    }
12}
13
14impl std::error::Error for JoinError {}
15
16/// Returns the start of the current runtime turn.
17///
18/// Tasks polled in the same turn observe the same instant, see
19/// [`Runtime::now`]. Returns [`Instant::now()`] outside of a runtime.
20#[inline]
21pub fn now() -> Instant {
22    crate::rt::Runtime::current_now()
23}
24
25#[track_caller]
26pub fn spawn<F>(fut: F) -> JoinHandle<F::Output>
27where
28    F: Future + 'static,
29{
30    let location = std::panic::Location::caller();
31    let fut = crate::task::wrap(fut);
32    crate::rt::Runtime::with_current(|rt| unsafe { rt.spawn_at(fut, location) })
33}
34
35/// Spawns a future on the current thread without a join handle.
36///
37/// The output is dropped when the task completes. Unlike dropping the
38/// [`JoinHandle`] returned by [`spawn()`], this does not allocate a handle.
39///
40/// # Panics
41///
42/// This function panics if ntex system is not running.
43#[track_caller]
44pub fn spawn_detached<F>(fut: F)
45where
46    F: Future + 'static,
47{
48    let location = std::panic::Location::caller();
49    let fut = crate::task::wrap(fut);
50    crate::rt::Runtime::with_current(|rt| unsafe { rt.spawn_detached_at(fut, location) });
51}