Search code examples
rusttimer

Can you tell me how to use a timer in 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;  
        }
    }
}

Solution

  • 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;
                }
                _ => (),
            }
        }
    }