Skip to main content

spawn

Function spawn 

Source
pub fn spawn<F, T>(future: F) -> JoinHandle<T>
where F: Future<Output = T> + Send + 'static, T: Send + 'static,
Expand description

Spawns a task.

This function is similar to std::thread::spawn, except it spawns an asynchronous task.

ยงExamples

use async_std::task;

let handle = task::spawn(async {
    1 + 2
});

assert_eq!(handle.await, 3);
Examples found in repository?
examples/supervisor_clear_send_later.rs (lines 47-49)
43async fn main() -> Result<(), Box<dyn std::error::Error>> {
44    let service_supervisor = xactor::Supervisor::start(PingLater::default).await?;
45    let service_addr = service_supervisor.clone();
46
47    let supervisor_task = xactor::spawn(async {
48        service_supervisor.wait_for_stop().await;
49    });
50
51    let send_ping = async {
52        println!("  main  :: sending Ping");
53        service_addr.send(Ping("before halt")).unwrap();
54    };
55
56    let send_halt = async {
57        xactor::sleep(Duration::from_millis(1_000)).await;
58        println!("  main  :: sending Halt");
59        service_addr.send(Halt).unwrap();
60    };
61
62    let _ = futures::join!(supervisor_task, send_halt, send_ping);
63
64    Ok(())
65}
More examples
Hide additional examples
examples/supervisor_clear_interval.rs (lines 72-74)
68async fn main() -> Result<(), Box<dyn std::error::Error>> {
69    let service_supervisor = xactor::Supervisor::start(PingTimer::default).await?;
70    let service_addr = service_supervisor.clone();
71
72    let supervisor_task = xactor::spawn(async {
73        service_supervisor.wait_for_stop().await;
74    });
75
76    let send_halt = async {
77        xactor::sleep(Duration::from_millis(5_200)).await;
78        println!("  main  :: sending Halt");
79        service_addr.send(Halt).unwrap();
80    };
81
82    let _ = futures::join!(supervisor_task, send_halt);
83    // run this to see that the interval is not properly stopped if the ctx is stopped
84    // futures::join!(supervisor_task, send_panic); // there is no panic recovery
85
86    Ok(())
87}