supervisor_clear_send_later/
supervisor_clear_send_later.rs

1use std::time::Duration;
2use xactor::{message, Actor, Context, Handler};
3
4#[derive(Debug, Default)]
5pub struct PingLater;
6
7#[async_trait::async_trait]
8impl Actor for PingLater {
9    async fn started(&mut self, ctx: &mut Context<Self>) -> xactor::Result<()> {
10        ctx.send_later(Ping("after halt"), Duration::from_millis(1_500));
11
12        Ok(())
13    }
14    /// Called after an actor is stopped.
15    async fn stopped(&mut self, _: &mut Context<Self>) {
16        println!("PingLater:: stopped()");
17    }
18}
19
20#[message]
21#[derive(Debug)]
22struct Ping(&'static str);
23
24#[async_trait::async_trait]
25impl Handler<Ping> for PingLater {
26    async fn handle(&mut self, _ctx: &mut Context<Self>, msg: Ping) {
27        println!("PingLater:: handle {:?}", msg);
28    }
29}
30#[message]
31struct Halt;
32
33#[async_trait::async_trait]
34impl Handler<Halt> for PingLater {
35    async fn handle(&mut self, ctx: &mut Context<Self>, _msg: Halt) {
36        println!("PingLater:: received Halt");
37        ctx.stop(None);
38        println!("PingLater:: stopped");
39    }
40}
41
42#[xactor::main]
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}