aral_runtime_tokio/task/
mod.rs

1use std::{
2    any::Any,
3    future::Future,
4    pin::{pin, Pin},
5    result,
6    task::{Context, Poll},
7    time::Duration,
8};
9
10#[inline]
11pub async fn sleep(duration: Duration) {
12    tokio::time::sleep(duration).await
13}
14
15pub struct JoinHandle<T>(tokio::task::JoinHandle<T>);
16
17impl<T> JoinHandle<T> {
18    pub async fn cancel(self) -> Option<T> {
19        self.0.abort();
20        self.0.await.ok()
21    }
22}
23
24impl<T> Future for JoinHandle<T> {
25    type Output = result::Result<T, Box<dyn Any + Send + 'static>>;
26
27    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
28        pin!(&mut self.0)
29            .poll(cx)
30            .map(|r| r.map_err(|err| err.into_panic()))
31    }
32}
33
34#[inline]
35pub fn spawn<T: Send + 'static>(future: impl Future<Output = T> + Send + 'static) -> JoinHandle<T> {
36    JoinHandle(tokio::spawn(future))
37}
38
39#[inline]
40pub fn spawn_blocking<T: Send + 'static>(f: impl FnOnce() -> T + Send + 'static) -> JoinHandle<T> {
41    JoinHandle(tokio::task::spawn_blocking(f))
42}