Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use Tokio to trigger a function every period or interval in seconds?

In Node.js I can set the interval that a certain event should be triggered,

function intervalFunc() {
  console.log('whelp, triggered again!');
}

setInterval(intervalFunc, 1500);

However the interface for Tokio's interval is a bit more complex. It seems to be a something to do with a much more literal definition of an interval, and rather than calling a function at an interval, it simply stalls the thread until the time passes (with .await).

Is there a primitive in Tokio that calls a function "every x seconds" or the like? If not, is there an idiom that has emerged to do this?

I only need to run one function on a recurring interval... I don't care about other threads either. It's just one function on Tokio's event loop.

like image 836
NO WAR WITH RUSSIA Avatar asked Jan 25 '23 10:01

NO WAR WITH RUSSIA


1 Answers

Spawn a Tokio task to do something forever:

use std::time::Duration;
use tokio::{task, time}; // 1.3.0

#[tokio::main]
async fn main() {
    let forever = task::spawn(async {
        let mut interval = time::interval(Duration::from_millis(10));

        loop {
            interval.tick().await;
            do_something().await;
        }
    });

    forever.await;
}

You can also use tokio::time::interval to create a value that you can tick repeatedly. Perform the tick and call your function inside of the body of stream::unfold to create a stream:

use futures::{stream, StreamExt}; // 0.3.13
use std::time::{Duration, Instant};
use tokio::time; // 1.3.0

#[tokio::main]
async fn main() {
    let interval = time::interval(Duration::from_millis(10));

    let forever = stream::unfold(interval, |mut interval| async {
        interval.tick().await;
        do_something().await;
        Some(((), interval))
    });

    let now = Instant::now();
    forever.for_each(|_| async {}).await;
}

async fn do_something() {
    eprintln!("do_something");
}

See also:

  • How can I run a set of functions concurrently on a recurring interval without running the same function at the same time using Tokio?
like image 181
Shepmaster Avatar answered Jan 29 '23 22:01

Shepmaster