Skip to main content

Task

Struct Task 

Source
pub struct Task<Fut>(/* private fields */);
Expand description

An actor that runs a future and is associated bidirectionally with its lifecycle: the actor dying stops the task, and the task dying kills the actor.

To support background tasks, Task holds its own ActorRef – it doesn’t die if you don’t hold a reference to it.

Kameo doesn’t natively provide functionality for this – ActorRef::attach_stream is the closest thing, but it doesn’t fit the mental model of a background task that doesn’t necessarily produce messages. So instead this is a thin wrapper around tokio::spawn, and the inner future kills the actor if the future completes.

Task implements Message<Infallible> so it can be addressed as a type-erased Recipient even though it doesn’t accept any messages.

If you need to be generic over the task future or would need to name the type of an anonymous future, it’s recommended to box the future and use ErasedTask as the task type.

§Examples

Spawning a task that shares lifecycle with a parent:

struct Parent;

impl Actor for Parent {
    type Error = ();
    type Args = ();

    async fn on_start(_: (), slf: ActorRef<Self>) -> Result<Self, ()> {
        Task::spawn_link(&slf, async move {
            for i in 0.. {
                println!("{i}");
                tokio::time::sleep(Duration::from_millis(25)).await;
            }
        });

        // ... other self-init ...

        Ok(Self)
    }
}

let parent = Parent::spawn(());
tokio::time::sleep(Duration::from_millis(99)).await;
parent.kill();
// prints 0, 1, 2, 3, then the parent and task are killed

Trait Implementations§

Source§

impl<Fut> Actor for Task<Fut>
where Fut: Future<Output = ()> + Send + 'static,

Source§

type Args = Fut

Arguments to initialize the actor. Read more
Source§

type Error = Infallible

Actor error type. Read more
Source§

async fn on_start( fut: Self::Args, slf: ActorRef<Self>, ) -> Result<Self, Self::Error>

Called when the actor starts, before it processes any messages. Read more
Source§

async fn on_stop( &mut self, slf: WeakActorRef<Self>, reason: ActorStopReason, ) -> Result<(), Self::Error>

Called before the actor stops. Read more
Source§

fn name() -> &'static str

The name of the actor, which can be useful for logging or debugging. Read more
Source§

fn supervision_strategy() -> SupervisionStrategy

Defines the supervision strategy for this actor when acting as a supervisor. Read more
Source§

fn on_message( &mut self, msg: Box<dyn DynMessage<Self>>, actor_ref: ActorRef<Self>, tx: Option<Sender<Result<Box<dyn Any + Send>, SendError<Box<dyn Any + Send>, Box<dyn Any + Send>>>>>, stop: &mut bool, ) -> impl Future<Output = Result<(), Box<dyn ReplyError>>> + Send

Called when the actor receives a message to be processed. Read more
Source§

fn on_panic( &mut self, actor_ref: WeakActorRef<Self>, err: PanicError, ) -> impl Future<Output = Result<ControlFlow<ActorStopReason>, Self::Error>> + Send

Called when the actor encounters a panic or an error during “tell” message handling. Read more
Called when a linked actor dies. Read more
Source§

fn next( &mut self, actor_ref: WeakActorRef<Self>, mailbox_rx: &mut MailboxReceiver<Self>, ) -> impl Future<Output = Result<Option<Signal<Self>>, Self::Error>> + Send

Awaits the next signal typically from the mailbox. Read more
Source§

impl<Fut> Message<Infallible> for Task<Fut>
where Fut: Future<Output = ()> + Send + 'static,

Source§

type Reply = Infallible

The reply sent back to the message caller.
Source§

async fn handle( &mut self, _: Infallible, _: &mut Context<Self, Self::Reply>, ) -> Infallible

Handler for this message.
Source§

fn name() -> &'static str

The name of the message, which can be useful for logging or debugging. Read more

Auto Trait Implementations§

§

impl<Fut> Freeze for Task<Fut>

§

impl<Fut> RefUnwindSafe for Task<Fut>
where Fut: RefUnwindSafe,

§

impl<Fut> Send for Task<Fut>
where Fut: Send,

§

impl<Fut> Sync for Task<Fut>
where Fut: Sync,

§

impl<Fut> Unpin for Task<Fut>
where Fut: Unpin,

§

impl<Fut> UnsafeUnpin for Task<Fut>

§

impl<Fut> UnwindSafe for Task<Fut>
where Fut: UnwindSafe,

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<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<T> Downcast for T
where T: Any,

Source§

fn into_any(self: Box<T>) -> Box<dyn Any>

Converts Box<dyn Trait> (where Trait: Downcast) to Box<dyn Any>, which can then be downcast into Box<dyn ConcreteType> where ConcreteType implements Trait.
Source§

fn into_any_rc(self: Rc<T>) -> Rc<dyn Any>

Converts Rc<Trait> (where Trait: Downcast) to Rc<Any>, which can then be further downcast into Rc<ConcreteType> where ConcreteType implements Trait.
Source§

fn as_any(&self) -> &(dyn Any + 'static)

Converts &Trait (where Trait: Downcast) to &Any. This is needed since Rust cannot generate &Any’s vtable from &Trait’s.
Source§

fn as_any_mut(&mut self) -> &mut (dyn Any + 'static)

Converts &mut Trait (where Trait: Downcast) to &Any. This is needed since Rust cannot generate &mut Any’s vtable from &mut Trait’s.
Source§

impl<T> DowncastSend for T
where T: Any + Send,

Source§

fn into_any_send(self: Box<T>) -> Box<dyn Any + Send>

Converts Box<Trait> (where Trait: DowncastSend) to Box<dyn Any + Send>, which can then be downcast into Box<ConcreteType> where ConcreteType implements Trait.
Source§

impl<T> DowncastSync for T
where T: Any + Send + Sync,

Source§

fn into_any_sync(self: Box<T>) -> Box<dyn Any + Send + Sync>

Converts Box<Trait> (where Trait: DowncastSync) to Box<dyn Any + Send + Sync>, which can then be downcast into Box<ConcreteType> where ConcreteType implements Trait.
Source§

fn into_any_arc(self: Arc<T>) -> Arc<dyn Any + Send + Sync>

Converts Arc<Trait> (where Trait: DowncastSync) to Arc<Any>, which can then be downcast into Arc<ConcreteType> where ConcreteType implements Trait.
Source§

impl<A, T> DynMessage<A> for T
where A: Actor + Message<T>, T: Send + 'static,

Source§

fn handle_dyn<'a>( self: Box<T>, state: &'a mut A, actor_ref: ActorRef<A>, tx: Option<Sender<Result<Box<dyn Any + Send>, SendError<Box<dyn Any + Send>, Box<dyn Any + Send>>>>>, stop: &'a mut bool, ) -> Pin<Box<dyn Future<Output = Result<(), Box<dyn ReplyError>>> + Send + 'a>>

Handles the dyn message with the provided actor state, ref, and reply sender.
Source§

fn as_any(self: Box<T>) -> Box<dyn Any>

Casts the type to a Box<dyn Any>.
Source§

impl<T> ErasedDestructor for T
where T: 'static,

Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
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> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T> Read<Exclusive, BecauseExclusive> for T
where T: ?Sized,

Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<A> Spawn for A
where A: Actor,

Source§

fn spawn(args: Self::Args) -> ActorRef<Self>

Spawns the actor in a Tokio task, running asynchronously with a default bounded mailbox. Read more
Source§

fn spawn_default() -> ActorRef<Self>
where Self::Args: Default,

Spawns the actor with default initialization in a Tokio task. Read more
Source§

fn spawn_with_mailbox( args: Self::Args, _: (MailboxSender<Self>, MailboxReceiver<Self>), ) -> ActorRef<Self>

Spawns the actor in a Tokio task with a specific mailbox configuration. Read more
Spawns and links the actor in a Tokio task with a default bounded mailbox. Read more
Spawns and links the actor in a Tokio task with a specific mailbox configuration. Read more
Source§

fn spawn_in_thread(args: Self::Args) -> ActorRef<Self>

Spawns the actor in its own dedicated thread with a default bounded mailbox. Read more
Source§

fn spawn_in_thread_with_mailbox( args: Self::Args, _: (MailboxSender<Self>, MailboxReceiver<Self>), ) -> ActorRef<Self>

Spawns the actor in its own dedicated thread with a specific mailbox configuration. Read more
Source§

fn prepare() -> PreparedActor<Self>

Creates a new prepared actor, allowing access to its ActorRef before spawning. Read more
Source§

fn prepare_with_mailbox( _: (MailboxSender<Self>, MailboxReceiver<Self>), ) -> PreparedActor<Self>

Creates a new prepared actor with a specific mailbox configuration, allowing access to its ActorRef before spawning. Read more
Source§

fn supervise<A>( supervisor_ref: &ActorRef<A>, args: Self::Args, ) -> SupervisedActorBuilder<'_, A, Self>
where A: Actor, Self::Args: Clone + Sync,

Creates a supervised child actor under a supervisor. Read more
Source§

fn supervise_with<A>( supervisor_ref: &ActorRef<A>, f: impl Fn() -> Self::Args + Send + Sync + 'static, ) -> SupervisedActorBuilder<'_, A, Self>
where A: Actor,

Creates a supervised child actor with a factory function for generating args. Read more
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.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more