-
Hi guys: I want to run a struct function repeatedly in a tokio spawn like follow: pub fn keep_alive(&self, node: &Node) -> ResultType<()> {
println!("keep alive...");
let node_clone = node.clone();
tokio::spawn(async move {
let mut timer = interval(Duration::from_secs(2));
loop {
tokio::select! {
_ = timer.tick() => {
self.send_action(&node_clone, Action::UPDATE).ok();
}
}
}
});
Ok(())
} but I got the tokio::spawn(async move {
| ^^^^^^^^^^^^ lifetime `'static` required I am trying to add the shared self in code: pub fn keep_alive(&self, node: &Node) -> ResultType<()> {
println!("keep alive...");
let node_clone = node.clone();
let shared_self = Arc::new(self);
tokio::spawn(async move {
let mut timer = interval(Duration::from_secs(2));
let self_ref = shared_self.clone();
loop {
tokio::select! {
_ = timer.tick() => {
self_ref.send_action(&node_clone, Action::UPDATE).ok();
}
}
}
});
Ok(())
} 148 | pub fn keep_alive(&self, node: &Node) -> ResultType<()> {
| ----- this data with an anonymous lifetime `'_`...
...
152 | let shared_self = Arc::new(self);
| ^^^^ ...is captured here...
153 | tokio::spawn(async move {
| ------------ ...and is required to live as long as `'static` here But it doesn't work. What to do about this situation to fix that? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
The type you are creating with the shared self is an Check out this article for a description of how to accomplish this kind of thing. The general idea in the article is to split your struct into two structs so that you don't need to share it in the first place. |
Beta Was this translation helpful? Give feedback.
The type you are creating with the shared self is an
Arc<&Self>
, which has a reference inside it, but to use anArc
, the struct must go inside theArc
without an ampersand.Check out this article for a description of how to accomplish this kind of thing. The general idea in the article is to split your struct into two structs so that you don't need to share it in the first place.