Im trying to learn a bit more about tokio by making a scheduling engine, tho i run into an issue for the following code:
async fn refresh(self: &Arc<Self>) {
if let Some(process) = self.task_process.swap(None) {
process.abort()
}
if self.reference.lock().await.is_empty() {
return;
}
let (id, task, time) = self.get_next().await.unwrap();
let this = Arc::clone(self);
self.task_process.swap(Some(Arc::new(
tokio::spawn(async move {
let now_chrono = Local::now();
let now_tokio = Instant::now();
let delta = time.signed_duration_since(now_chrono);
let target_time = if delta.num_milliseconds() <= 0 {
now_tokio
} else {
now_tokio + Duration::from_millis(delta.num_milliseconds() as u64)
};
sleep_until(target_time).await;
{
let mut lock = task.lock().await;
lock.execute().await.unwrap();
let runs = lock.total_runs().await;
lock.set_total_runs(runs + 1).await;
}
// vv Panicks vv
tokio::task::spawn_local(async move {
this.clone().refresh().await;
});
})
)));
}
the panic in question is:
spawn_local` called from outside of a `task::LocalSet` or LocalRuntime
If i try to make it a spawn, then i get a compile-time error:
error: future cannot be sent between threads safely
--> ...
|
185 | / tokio::spawn(async move {
186 | | this.clone().refresh().await;
187 | | });
| |__________________^ future created by async block is not `Send`