使用 actix 启动计划任务并访问 self
Lauch scheduled task with actix and access to self
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);
}
}
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);
}
}