j3ans
October 31, 2020, 3:05pm
1
Hi!
I have a simple actix web service with some endpoints and a shared state. I would like to each ten seconds run a function to update the state. Is there a way to do this with actix api or must I use a lib like https://github.com/lholden/job_scheduler ?
Thx
alice
October 31, 2020, 3:18pm
2
Actix internally uses Tokio for its tasks, so you can just spawn an ordinary Tokio task.
tokio::spawn(async move {
let interval = tokio::time::interval(Duration::from_secs(10));
loop {
interval.tick().await;
do_the_thing();
}
});
1 Like
j3ans
November 1, 2020, 1:19pm
5
It's ok to have a system like this?
#[actix_web::main]
async fn main() -> std::io::Result<()> {
let rt = Runtime::new().unwrap();
jobs::launch(&rt);
//The server start after
}
fn create_periodically_task(rt: &Runtime, duration_in_secs: u64) {
rt.spawn(async move {
let mut interval = interval(Duration::from_secs(duration_in_secs));
loop {
interval.tick().await;
println!("This task run every {} seconds ", duration_in_secs);
}
});
}
struct Task {
every: u64
}
pub fn launch(rt: &Runtime) {
let mut tasks = Vec::new();
// Add a task to run every 10 seconds
tasks.push(Task { every: 10 });
// Add a task to run every 30 seconds
tasks.push(Task { every: 30 });
// Add a task to run every minutes
tasks.push(Task { every: 60 });
for task in tasks {
create_periodically_task(rt, task.every);
}
}
alice
November 1, 2020, 1:40pm
6
You shouldn't create another runtime. The #[actix_web::main] macro already creates one for you (unless I've misunderstood something). Just call the tokio::spawn function directly.
j3ans
November 1, 2020, 1:48pm
7
If I use tokio::spawn directly without extra runtime, the app panics with the error message: must be called from the context of Tokio runtime
alice
November 1, 2020, 2:22pm
8
Make sure the versions of Tokio match up. Actix probably still uses Tokio 0.2.
j3ans
November 1, 2020, 4:44pm
9
Ok I will check the version thanks!
It's bad to have another runtime?
alice
November 1, 2020, 4:59pm
10
Well it's inefficient at least.
j3ans
November 1, 2020, 5:04pm
11
I downgraded the Tokio version to 0.2.22 and it works!
Thanks again @alice
2 Likes
system
Closed
January 30, 2021, 5:04pm
12
This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.