pub struct Context<A> { /* private fields */ }Expand description
Available to the actor in every execution call.
The context is used to interact with the actor system. You can start intervals, send messages to yourself, and stop the actor.
Implementations§
Source§impl<A: Actor> Context<A>
§Child Actors
impl<A: Actor> Context<A>
§Child Actors
Sourcepub fn add_child(&mut self, child: impl Into<Sender<()>>)
pub fn add_child(&mut self, child: impl Into<Sender<()>>)
Add a child actor.
This child actor is held until this context is stopped.
Sourcepub fn register_child<M: Message<Response = ()>>(
&mut self,
child: impl Into<Sender<M>>,
)
pub fn register_child<M: Message<Response = ()>>( &mut self, child: impl Into<Sender<M>>, )
Register a child actor by Message type.
This actor will be held until this actor is stopped via a Sender.
Sourcepub fn send_to_children<M: Message<Response = ()> + Clone>(
&mut self,
message: M,
)
pub fn send_to_children<M: Message<Response = ()> + Clone>( &mut self, message: M, )
Send a message to all child actors registered with this message type.
Sourcepub fn gc(&mut self)
pub fn gc(&mut self)
Perform context-local garbage collection.
This method:
- Removes child actors that have fully stopped.
- Drops join handles for background tasks that have already finished.
Running tasks and live child actors are not affected: this method does not cancel or stop anything that is still in progress. It only cleans up bookkeeping for work that has already completed.
§When to call this
gc is not called automatically by the runtime. If your actor spawns
many short‑lived tasks or children, you should call gc periodically to
release their resources from the Context. A common pattern is to call it:
- At the end of a message handler that may have spawned new tasks.
- On a timer or in response to a “maintenance” message.
For actors that rarely spawn tasks or children, calling gc occasionally
(or not at all) may be sufficient.
§Performance
gc iterates over all tracked tasks and children to remove completed ones.
The cost is roughly proportional to the number of entries being tracked.
It is typically inexpensive for a modest number of tasks, but if your actor
tracks many thousands of tasks you may want to adjust how often you call
gc to balance cleanup latency against overhead.
§Example
impl Handler<MyMessage> for MyActor {
type Response = ();
fn handle(&mut self, msg: MyMessage, ctx: &mut Context<Self>) {
// Potentially spawn a new background task or child here...
// Periodically clean up finished tasks and stopped children.
ctx.gc();
}
}Source§impl<A: Actor> Context<A>
§Creating Addrs, Callers and Senders to yourself
impl<A: Actor> Context<A>
§Creating Addrs, Callers and Senders to yourself
Sourcepub fn weak_address(&self) -> WeakAddr<A>
pub fn weak_address(&self) -> WeakAddr<A>
Create a weak address to the actor.
Sourcepub fn weak_sender<M: Message<Response = ()>>(&self) -> WeakSender<M>where
A: Handler<M>,
pub fn weak_sender<M: Message<Response = ()>>(&self) -> WeakSender<M>where
A: Handler<M>,
Create a weak sender to the actor.
Sourcepub fn weak_caller<M: Message<Response = R>, R>(&self) -> WeakCaller<M>where
A: Handler<M>,
pub fn weak_caller<M: Message<Response = R>, R>(&self) -> WeakCaller<M>where
A: Handler<M>,
Create a weak caller to the actor.
Source§impl<A: Actor> Context<A>
§Broker Interaction
impl<A: Actor> Context<A>
§Broker Interaction
Source§impl<A: Actor> Context<A>
§Task Handling
impl<A: Actor> Context<A>
§Task Handling
Sourcepub fn spawn_task(
&mut self,
task: impl Future<Output = ()> + Send + 'static,
) -> TaskHandle
pub fn spawn_task( &mut self, task: impl Future<Output = ()> + Send + 'static, ) -> TaskHandle
Spawn a task that will be executed in the background.
The task will be aborted when the actor is stopped.
Returns a TaskHandle that can be used to check if the task is finished
or to stop it manually using Context::stop_task.
§Example
impl Handler<StartWork> for MyActor {
async fn handle(&mut self, ctx: &mut Context<Self>, _: StartWork) {
let handle = ctx.spawn_task(async {
// Long-running background work
do_work().await;
});
// Check if task is still running
if let Some(false) = ctx.is_task_finished(&handle) {
println!("Task is still running");
}
// Optionally stop it later
ctx.stop_task(handle);
}
}Sourcepub fn interval<M: Message<Response = ()> + Clone + Send + 'static>(
&mut self,
message: M,
duration: Duration,
) -> TaskHandle
pub fn interval<M: Message<Response = ()> + Clone + Send + 'static>( &mut self, message: M, duration: Duration, ) -> TaskHandle
Send yourself a message at a regular interval.
§Backpressure
Ticks that take longer than 50% of the interval duration to send are skipped to prevent stale message buildup when the actor cannot keep pace with the interval.
Sourcepub fn interval_with<M: Message<Response = ()>>(
&mut self,
message_fn: impl Fn() -> M + Send + Sync + 'static,
duration: Duration,
) -> TaskHandlewhere
A: Handler<M>,
pub fn interval_with<M: Message<Response = ()>>(
&mut self,
message_fn: impl Fn() -> M + Send + Sync + 'static,
duration: Duration,
) -> TaskHandlewhere
A: Handler<M>,
Send yourself a message at a regular interval.
§Backpressure
Ticks that take longer than 50% of the interval duration to send are skipped to prevent stale message buildup when the actor cannot keep pace with the interval.
Warning: don’t do anything expensive in the message function, as it will block the interval.
Sourcepub fn delayed_send<M: Message<Response = ()>>(
&mut self,
message_fn: impl Fn() -> M + Send + Sync + 'static,
duration: Duration,
) -> TaskHandlewhere
A: Handler<M>,
pub fn delayed_send<M: Message<Response = ()>>(
&mut self,
message_fn: impl Fn() -> M + Send + Sync + 'static,
duration: Duration,
) -> TaskHandlewhere
A: Handler<M>,
Send yourself a message after a delay.
Sourcepub fn delayed_exec<F: Future<Output = ()> + Send + 'static>(
&mut self,
task: F,
duration: Duration,
) -> TaskHandle
pub fn delayed_exec<F: Future<Output = ()> + Send + 'static>( &mut self, task: F, duration: Duration, ) -> TaskHandle
Execute a task after a delay.
Sourcepub fn is_task_finished(&self, handle: &TaskHandle) -> Option<bool>
pub fn is_task_finished(&self, handle: &TaskHandle) -> Option<bool>
Check if a task is finished.
Returns None if the task handle is invalid (task was already removed).
Sourcepub fn stop_task(&mut self, handle: TaskHandle)
pub fn stop_task(&mut self, handle: TaskHandle)
Stop a specific task by aborting it and removing it from the task list.
Source§impl<A: RestartableActor> Context<A>
Life-cycle
impl<A: RestartableActor> Context<A>
Life-cycle
Sourcepub fn restart(&self) -> Result<()>
pub fn restart(&self) -> Result<()>
Restart the actor.
The behavior depends on the restart strategy configured via the builder:
§RestartOnly (default)
Calls Actor::stopped() then Actor::started() on the same instance.
The actor’s state is preserved—only the lifecycle hooks are re-triggered.
This is the default when using hannibal::setup_actor().
§RecreateFromDefault
Calls Actor::stopped(), creates a new instance via Default::default(),
then calls Actor::started(). All previous state is discarded.
Enable this with ActorBuilder::recreate_from_default().
§Note: Stream Actors
Actors spawned with ActorBuilder::on_stream()
cannot be restarted, as streams cannot be replayed.