rustrust-actix

Lauch scheduled task with actix and access to self


new on rust, i have some problem to handle async and lifetime in rust.

I try to run a scheduled task into an Actix runtime (actix-web)
I'm blocked cause of lifetime.

I got this errror:

  error[E0495]: cannot infer an appropriate lifetime for autoref due to conflicting requirements  
  -> this.execute().into_actor(this)

Code :

use actix::prelude::*;
use std::time::Duration;

pub struct SleepUnusedCloneTask {
    pub count: i32
}

impl Actor for SleepUnusedCloneTask {
    type Context = Context<Self>;

    fn started(&mut self, ctx: &mut Self::Context) {
        ctx.run_interval(Duration::from_millis(100), |this, ctx| {
            ctx.spawn(
                this.execute().into_actor(this)
            );
        });
    }
}

impl SleepUnusedCloneTask {
    async fn execute(&mut self)  {
        println!("Flood: {}", self.count);
    }
}

And in my main function :

let _sleep_unused_task = SleepUnusedCloneTask::create(move |_| {
    SleepUnusedCloneTask { count: 5 }
});

Solution

  • Can be solve with Arc and clone ;)

    use actix::prelude::*;
    use std::time::Duration;
    
    pub struct Task {
        pub count: Arc<i32>
    }
    
    impl Actor for Task {
        type Context = Context<Self>;
    
        fn started(&mut self, ctx: &mut Self::Context) {
            ctx.run_interval(Duration::from_millis(100), |this, ctx| {
                Arbiter::spawn(Task::execute(this.count.clone()));
            });
        }
    }
    
    impl Task {
        async fn execute(count: Arc<i32>)  {
            println!("Flood: {}", self.count);
        }
    }