Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you tell me how to use a timer in Rust?

Tags:

timer

rust

Can you tell me how to use a timer in Rust? I need it to close after a certain time after entering the loop, use the break.

I used this, but it is necessary not after the start, but after entering the cycle.

use std::time::{Duration, Instant};

fn main() {
    let seconds = Duration::from_secs(5);  

    let start = Instant::now();
    loop {
       

        if Instant::now() - start >= seconds { 
            return;  
        }
    }
}

1 Answers

Use SystemTime::now().

An example from SystemTime docs:

use std::time::{Duration, SystemTime};
use std::thread::sleep;

fn main() {
   let now = SystemTime::now();

   // we sleep for 2 seconds
   sleep(Duration::new(2, 0));
   match now.elapsed() {
       Ok(elapsed) => {
           // it prints '2'
           println!("{}", elapsed.as_secs());
       }
       Err(e) => {
           // an error occurred!
           println!("Error: {e:?}");
       }
   }
}

And your code could look like this

use std::time::{Duration, SystemTime};

fn main() {
    let seconds = Duration::from_secs(5);

    let start = SystemTime::now();
    loop {
        // Делаем что-то.
        std::thread::sleep(Duration::new(2, 0));

        match start.elapsed() {
            Ok(elapsed) if elapsed > seconds => {
                return;
            }
            _ => (),
        }
    }
}
like image 116
denis.peplin Avatar answered Oct 17 '25 21:10

denis.peplin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!