diff --git a/Cargo.lock b/Cargo.lock index 69fb6af..2ad2481 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -475,6 +475,7 @@ checksum = "ff360e02eab121e0bc37a2d3b4d4dc622e6eda3a8e5253d5435ecf5bd4c68408" dependencies = [ "pin-project-lite", "tokio-macros", + "tracing", ] [[package]] diff --git a/Cargo.toml b/Cargo.toml index b398592..e8f2ff3 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -58,10 +58,11 @@ missing_debug_implementations = "warn" # dependencies require a feature enabled when using `--cfg docsrs` which # we can not do. To enable for a crate set # `#![cfg_attr(n0_future_docsrs, feature(doc_auto_cfg))]` in the crate. -unexpected_cfgs = { level = "warn", check-cfg = ["cfg(n0_future_docsrs)"] } +unexpected_cfgs = { level = "warn", check-cfg = ["cfg(n0_future_docsrs)", "cfg(tokio_unstable)"] } [lints.clippy] unused-async = "warn" [features] serde = ["web-time/serde"] +tracing = ["tokio/tracing"] diff --git a/src/task.rs b/src/task.rs index e4b755e..eaf5198 100644 --- a/src/task.rs +++ b/src/task.rs @@ -3,6 +3,36 @@ #[cfg(not(wasm_browser))] pub use tokio::spawn; + +/// Spawns a future as a task. +/// +/// If possible uses `name` to name the task +#[cfg(all(not(wasm_browser), not(tokio_unstable)))] +#[track_caller] +pub fn spawn_with_name(_name: &str, future: F) -> JoinHandle +where + F: std::future::Future + Send + 'static, + F::Output: Send + 'static, +{ + spawn(future) +} + +/// Spawns a future as a task. +/// +/// If possible uses `name` to name the task +#[cfg(all(not(wasm_browser), tokio_unstable, feature = "tracing"))] +#[track_caller] +pub fn spawn_with_name(name: &str, future: F) -> JoinHandle +where + F: std::future::Future + Send + 'static, + F::Output: Send + 'static, +{ + tokio::task::Builder::new() + .name(name) + .spawn(future) + .expect("doesn't fails") +} + #[cfg(not(wasm_browser))] pub use tokio::task::{AbortHandle, Id, JoinError, JoinHandle, JoinSet}; #[cfg(not(wasm_browser))] @@ -548,6 +578,19 @@ mod wasm { handle } + + /// Spawns a future as a task in the browser runtime. + /// + /// If possible uses `name` to name the task + pub fn spawn_with_name( + _name: &str, + fut: impl IntoFuture + 'static, + ) -> JoinHandle + where + T: 'static, + { + spawn(fut) + } } #[cfg(test)] @@ -561,6 +604,14 @@ mod test { use crate::task; + #[test] + async fn task_with_name() { + let h1 = task::spawn_with_name("test", async { + crate::time::sleep(Duration::from_millis(10)).await; + }); + h1.await.unwrap(); + } + #[test] async fn task_abort() { let h1 = task::spawn(async {