关于锈的新知识,我在处理异步和锈的寿命时遇到了一些问题。
我尝试将计划的任务运行到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求解并克隆;)
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);
}
}