Expand description
Timers for sending messages to actors periodically
The methodology of timers in ractor are based on Erlang’s timer module.
We aren’t supporting all timer functions, as many of them don’t make sense but we
support the relevant ones for ractor. In short
- Send on a period
- Send after a delay
- Stop after a delay
- Kill after a delay
§Examples
use ractor::concurrency::Duration;
use ractor::Actor;
use ractor::ActorProcessingErr;
use ractor::ActorRef;
struct ExampleActor;
enum ExampleMessage {
AfterDelay,
OnPeriod,
}
#[cfg(feature = "cluster")]
impl ractor::Message for ExampleMessage {}
#[cfg_attr(feature = "async-trait", ractor::async_trait)]
impl Actor for ExampleActor {
type Msg = ExampleMessage;
type State = ();
type Arguments = ();
async fn pre_start(
&self,
_myself: ActorRef<Self::Msg>,
_args: Self::Arguments,
) -> Result<Self::State, ActorProcessingErr> {
println!("Starting");
Ok(())
}
async fn handle(
&self,
_myself: ActorRef<Self::Msg>,
message: Self::Msg,
_state: &mut Self::State,
) -> Result<(), ActorProcessingErr> {
match message {
ExampleMessage::AfterDelay => println!("After delay"),
ExampleMessage::OnPeriod => println!("On period"),
}
Ok(())
}
}
#[tokio::main]
async fn main() {
let (actor, handle) = Actor::spawn(None, ExampleActor, ())
.await
.expect("Failed to startup dummy actor");
// send the message after a 100ms delay
actor.send_after(Duration::from_millis(100), || ExampleMessage::AfterDelay);
// send this message every 10ms
actor.send_interval(Duration::from_millis(10), || ExampleMessage::OnPeriod);
// Exit the actor after 200ms (equivalent of calling `stop(maybe_reason)`)
actor.exit_after(Duration::from_millis(200));
// Kill the actor after 300ms (won't execute since we did stop before, but here
// as an example)
actor.kill_after(Duration::from_millis(300));
// wait for actor exit
handle.await.unwrap();
}Functions§
- exit_
after - Sends the stop signal to the actor after a specified duration, attaching a reason of “Exit after {}ms” by default
- kill_
after - Sends the KILL signal to the actor after a specified duration
- send_
after - Sends a message after a given period to the specified actor. The task terminates once the send has completed
- send_
interval - Sends a message to a given actor repeatedly after a specified time using the provided message generation function. The task will exit once the channel is closed (meaning the underlying crate::Actor has terminated)