What is the best way to run scheduled concurrent tasks in Rust?

I have an old program written in Java using Executors within the concurrency package. The program runs scheduled tasks (like cron jobs) and actively uses scheduleAtFixedRate and scheduleWithFixedDelay.

I am now porting the program to Rust.

I came across the scheduled-executor crate and it seemed that it tries to replicate the Java version. The problem is that the crate's last update was 3 years ago and seemed to be an abandoned project.

What are your recommendations? What is the best way to implement my requirements in Rust?

I use tokio for such tasks (if you are fine with using async).
tokio::time::interval and tokio::time::interval_at can replace scheduleAtFixedRate:

    let mut interval_timer = tokio::time::interval(chrono::Duration::days(1).to_std().unwrap());
    loop {
        // Wait for the next interval tick
        tokio::spawn(async { do_my_task().await; }); // For async task
        tokio::task::spawn_blocking(|| do_my_task()); // For blocking task

To replace scheduleWithFixedDelay you can call tokio::time::delay_for or tokio::time::delay_until at the end of your task execution to get the same effect, kinda like this:

loop {
    do_my_task().await; // For async task
        // For blocking task:
        let join_handle = tokio::task::spawn_blocking(|| do_my_task());
        join_handle.await; // TODO: should handle error here

Using async/await with Tokio may very well be the tool you're looking for. Can you talk a bit more about what kind of actions the scheduled tasks perform?

Thank you guys! Looking at the sample code, it looks like that's the answer.

The actions to perform would be to read RSS feeds.

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.