rust - 使用 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 }
});
解决方案
可以用 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);
}
}
推荐阅读
- google-sheets - 如何根据 Google 表格上不同工作表的条件提取唯一行
- angular - NGXS 状态返回对象而不是实际数据
- node.js - 指定跨域资源策略以防止资源被阻止
- javascript - array.includes doesn't work when checking if an iterator exists in array
- python - 在 Python 中按值对矩阵进行排序
- android-studio - 如何删除或最小化android studio资产文件夹中的Audience_Network.dex文件?
- java - Do a HTTP POST instead of a GET
- r - 使用 purrr 和 select 创建二分变量
- android - UriMatcher matching wilcard? (Crash in Android mail app)
- c++ - 当分子和分母都有一个有限的范围时,找到一个实数的有理逼近