Alborq
Alborq

Reputation: 39

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

Upvotes: 0

Views: 1458

Answers (2)

Samuel Gomez
Samuel Gomez

Reputation: 23

};

pub struct ScheduleActor {
    pub count: Arc<Mutex<i32>>,
    pub arbiter: ArbiterHandle,
}

impl ScheduleActor {
    pub fn new() -> Self {
        Self {
            count: Arc::new(Mutex::new(0)),
            arbiter: Arbiter::current(),
        }
    }
    async fn execute(count: Arc<Mutex<i32>>) {
        println!("Flood: {:?}", count);
    }
}

impl Default for ScheduleActor {
    fn default() -> Self {
        Self::new()
    }
}

impl Supervised for ScheduleActor {}

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

    fn started(&mut self, ctx: &mut Self::Context) {
        ctx.run_interval(Duration::from_millis(100), |this, _| {
            let mut increment = this.count.lock().unwrap();
            *increment += 1;
            let count = this.count.clone();

            this.arbiter
                .spawn(async move { Self::execute(count).await });
        });
    }
}

Upvotes: 0

Alborq
Alborq

Reputation: 39

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

Upvotes: 1

Related Questions