Skip to content

Instantly share code, notes, and snippets.

@guidomb
Created August 16, 2023 20:58
Show Gist options
  • Save guidomb/e28f757374c1d19ce11bab5c5bdc25c1 to your computer and use it in GitHub Desktop.
Save guidomb/e28f757374c1d19ce11bab5c5bdc25c1 to your computer and use it in GitHub Desktop.
use std::time::{Duration, Instant};
use actix::prelude::*;
use rand::Rng;
use tokio::time::sleep;
#[actix_rt::main]
async fn main() {
let actor = MyActor::start_default();
println!("Sending Ping(1)");
let ping1_fut = actor.send(Ping(1));
println!("Sending Ping(2)");
let ping2_fut = actor.send(Ping(2));
println!("Sending Ping(3)");
let ping3_fut = actor.send(Ping(3));
println!("Waiting for Ping(2) response");
let start = Instant::now();
let response = ping2_fut.await.unwrap();
let end = Instant::now();
let duration = end - start;
println!(
"Ping(2) response: {response}. Total wait time: {}",
duration.as_millis()
);
// println!("Waiting for Ping(1) response");
// let response = ping1_fut.await.unwrap();
// println!("Ping(1) response: {response}");
// println!("Waiting for Ping(3) response");
// let response = ping3_fut.await.unwrap();
// println!("Ping(3) response: {response}");
}
#[derive(Message)]
#[rtype(result = "String")]
struct Ping(usize);
#[derive(Default)]
struct MyActor {}
impl Actor for MyActor {
type Context = Context<Self>;
}
impl Handler<Ping> for MyActor {
type Result = ResponseFuture<String>;
fn handle(&mut self, msg: Ping, _ctx: &mut Self::Context) -> Self::Result {
Box::pin(async move {
let sleep_time = Duration::from_millis(random());
println!(
"{:#?}: Processing Ping({}) with sleep time {}",
std::thread::current().name().unwrap(),
msg.0,
sleep_time.as_millis()
);
sleep(sleep_time).await;
println!(
"{:#?}: Woke up from Ping({})",
std::thread::current().name().unwrap(),
msg.0
);
format!("Response to {}", msg.0)
})
}
}
fn random() -> u64 {
let mut rng = rand::thread_rng();
rng.gen_range(1000..=5000)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment