Skip to main content

Context

Struct Context 

Source
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>

§Life-cycle
Source

pub fn stop(&self) -> Result<()>

Stop the actor.

Source§

impl<A: Actor> Context<A>

§Child Actors
Source

pub fn add_child(&mut self, child: impl Into<Sender<()>>)

Add a child actor.

This child actor is held until this context is stopped.

Source

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.

Source

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.

Source

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
Source

pub fn weak_address(&self) -> WeakAddr<A>

Create a weak address to the actor.

Source

pub fn weak_sender<M: Message<Response = ()>>(&self) -> WeakSender<M>
where A: Handler<M>,

Create a weak sender to the actor.

Source

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
Source

pub async fn publish<M: Message<Response = ()> + Clone>( &self, message: M, ) -> Result<()>

Publish to the broker.

Every actor can publish messages to the broker which will be delivered to all actors that subscribe to the message.

Source

pub async fn subscribe<M: Message<Response = ()> + Clone>( &mut self, ) -> Result<()>
where A: Handler<M>,

Subscribe to a message.

The actor will receive all messages of this type.

Source§

impl<A: Actor> Context<A>

§Task Handling
Source

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);
    }
}
Source

pub fn interval<M: Message<Response = ()> + Clone + Send + 'static>( &mut self, message: M, duration: Duration, ) -> TaskHandle
where A: Handler<M> + Send + 'static,

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.

Source

pub fn interval_with<M: Message<Response = ()>>( &mut self, message_fn: impl Fn() -> M + Send + Sync + 'static, duration: Duration, ) -> TaskHandle
where 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.

Source

pub fn delayed_send<M: Message<Response = ()>>( &mut self, message_fn: impl Fn() -> M + Send + Sync + 'static, duration: Duration, ) -> TaskHandle
where A: Handler<M>,

Send yourself a message after a delay.

Source

pub fn delayed_exec<F: Future<Output = ()> + Send + 'static>( &mut self, task: F, duration: Duration, ) -> TaskHandle

Execute a task after a delay.

Source

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).

Source

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

Source

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.

Trait Implementations§

Source§

impl<A> Drop for Context<A>

Source§

fn drop(&mut self)

Executes the destructor for this type. Read more
Source§

fn pin_drop(self: Pin<&mut Self>)

🔬This is a nightly-only experimental API. (pin_ergonomics)
Execute the destructor for this type, but different to Drop::drop, it requires self to be pinned. Read more

Auto Trait Implementations§

§

impl<A> !RefUnwindSafe for Context<A>

§

impl<A> !UnwindSafe for Context<A>

§

impl<A> Freeze for Context<A>

§

impl<A> Send for Context<A>

§

impl<A> Sync for Context<A>

§

impl<A> Unpin for Context<A>

§

impl<A> UnsafeUnpin for Context<A>

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.