首页 > 解决方案 > 使用 actix 启动计划任务并访问自己

问题描述

rust 的新手,我在处理 rust 中的异步和生命周期时遇到了一些问题。

我尝试将计划任务运行到 Actix 运行时 (actix-web)
我被阻止了生命周期的原因。

我得到了这个错误:

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

代码 :

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

在我的主要功能中:

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

标签: rustrust-actix

解决方案


可以用 Arc 和 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);
    }
}

推荐阅读