Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,868 questions

51,791 answers

573 users

How to create a loop that runs with a delay in Rust

1 Answer

0 votes
use std::thread::sleep;
use std::time::{Duration, Instant};

fn main() {

    let interval = Duration::from_secs(1);
    let mut next_time = Instant::now() + interval;
    let mut i = 0;
    loop {
        println!("{:?}", next_time); 
        sleep(next_time - Instant::now());
        next_time += interval;
        i += 1;
        if i == 7 {
            break;
        }
    }
}

   
   
/*
run:

Instant { tv_sec: 874606, tv_nsec: 345730049 }
Instant { tv_sec: 874607, tv_nsec: 345730049 }
Instant { tv_sec: 874608, tv_nsec: 345730049 }
Instant { tv_sec: 874609, tv_nsec: 345730049 }
Instant { tv_sec: 874610, tv_nsec: 345730049 }
Instant { tv_sec: 874611, tv_nsec: 345730049 }
Instant { tv_sec: 874612, tv_nsec: 345730049 }

*/

 



answered Aug 7, 2024 by avibootz

Related questions

1 answer 95 views
1 answer 102 views
102 views asked May 4, 2023 by avibootz
1 answer 119 views
2 answers 133 views
1 answer 100 views
2 answers 142 views
...