Tokio and timers

Hello.
How to create timer in tokio 0.2.20?
I would like my timer to run my function every 1 second.

I searched the docs and found no answer.

Please, help.

I think this can help you tokio::time - Rust

I read it. And it didn't help me.

1 Like

Here's an example using tokio's time API:

async fn say_hi() {
    println!("Hi!");
}

#[tokio::main]
async fn main() {
    let mut delay = tokio::time::interval(std::time::Duration::from_secs(1));
    for _ in 0..5 {
        delay.tick().await;
        say_hi().await;
    }
}

Would something like this work?

use tokio::time::delay_for;
use std::time::Duration;

fn call_me() {
    println!("Hello")
}

#[tokio::main]
async fn main() {
    loop {
        delay_for(Duration::from_millis(1000)).await;
        call_me();
    }
}

@naim, @bjornmolin I need the timer code to run parallel to the main program code and that the data be synchronized. I want the timer to be "started in another thread" (as if).

I don't know if I wrote it correctly.

You can spawn the timer.

use tokio::time::{delay_for, interval, Duration};

fn call_me() {
    println!("Hello")
}

async fn manage_timer() {
    let mut interval = interval(Duration::from_millis(100));
    loop {
        interval.tick().await;
        call_me();
    }
}

#[tokio::main]
async fn main() {
    tokio::spawn(manage_timer());
    // do other stuff ... 
    delay_for(Duration::from_millis(1050)).await;
    
    // When main exits, all spawned tasks are killed.
}

playground

1 Like

I'm solved it.

 let mut old = Instant::now();

 async fn say_hi() { println!("Hi!"); }

 tokio::spawn(async move {
    loop {
       /// do something else
       let now = Instant::now();
       match now.checked_duration_since(old)
       {
        Some(dur) => {
            if dur.as_secs() == tokio::time::Duration::from_secs(1).as_secs()
            {
                old = Instant::now();
                say_hi().await;
            }
          },
         None => {}
      };
  }
  });

Your code will be leaving the CPU at 100% while it waits.

I forgot to add tokio::spawn to the example. Already corrected.

Your code is still leaving the CPU at 100% while it waits. You should use delay_for or interval to sleep in asynchronous code.

@alice Are you sure? In the htop shows me the utilization of 2-4% (for process).

Perhaps you are doing something where you put "/// do something else". In that case it might not use all of your cpu, but it risks being incorrect instead. What if the "do something else" spent more than one second, causing the dur.as_secs() to jump from 0 to 2?

Ok. I understand. Thx for reply.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.