-
Notifications
You must be signed in to change notification settings - Fork 2
/
interval.rs
97 lines (77 loc) · 2.38 KB
/
interval.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
use time::ext::NumericalStdDuration;
use uactor::actor::MessageSender;
use uactor::system::System;
use crate::actor1::Actor1;
use crate::actor1::Actor1Msg;
use crate::actor1::Actor1Ref;
use crate::messages::{PingMsg, PongMsg};
mod messages {
use uactor::message::{Message, Reply};
pub struct PingMsg(pub Reply<PongMsg>);
#[derive(Debug)]
pub struct PongMsg;
uactor::message_impl!(PingMsg, PongMsg);
}
mod actor1 {
use uactor::actor::{Actor, HandleResult, Handler};
use uactor::context::Context;
use uactor::message::IntervalMessage;
use crate::messages::{PingMsg, PongMsg};
#[derive(Default)]
pub struct Actor1 {
interval_count: u8,
}
impl Actor for Actor1 {
type Context = Context;
type Inject = ();
type State = ();
}
impl Handler<PingMsg> for Actor1 {
async fn handle(
&mut self,
_: &mut Self::Inject,
ping: PingMsg,
_ctx: &mut Context,
state: &Self::State,
) -> HandleResult {
println!("actor1: Received ping message");
let PingMsg(reply) = ping;
let _ = reply.send(PongMsg);
Ok(())
}
}
impl Handler<IntervalMessage> for Actor1 {
async fn handle(
&mut self,
_: &mut Self::Inject,
IntervalMessage {
time: _,
duration: _,
}: IntervalMessage,
_ctx: &mut Context,
state: &Self::State,
) -> HandleResult {
self.interval_count += 1;
println!(
"actor1: received {}nd interval message",
self.interval_count
);
Ok(())
}
}
uactor::generate_actor_ref!(Actor1, { PingMsg });
}
#[tokio::main]
async fn main() -> anyhow::Result<()> {
let actor1 = Actor1::default();
let mut system = System::global().build();
// 1 second interval
let interval = tokio::time::interval(1.std_seconds());
let (actor1_ref, _) = uactor::spawn_with_ref!(system, actor1: Actor1, interval);
system.run_actor::<Actor1>(actor1_ref.name()).await?;
let pong = actor1_ref.ask::<PongMsg>(PingMsg).await?;
println!("main: received {pong:?} message");
// waiting 10 seconds and expecting new message each 1 second
tokio::time::sleep(10.std_seconds()).await;
Ok(())
}