How can I put the current thread to sleep?

Tiago picture Tiago · Mar 9, 2015 · Viewed 11.5k times · Source

There is so much outdated information, it is really hard to find out how to sleep. I'd like something similar to this Java code:

Thread.sleep(4000);

Answer

Shepmaster picture Shepmaster · Mar 10, 2015

Rust 1.4+

Duration and sleep have returned and are stable!

use std::time::Duration;
use std::thread;

fn main() {
    thread::sleep(Duration::from_millis(4000))
}

You could also use Duration::from_secs(4), which might be more obvious in this case.

The solution below for 1.0 will continue to work if you prefer it, due to the nature of semantic versioning.

Rust 1.0+

Duration wasn't made stable in time for 1.0, so there's a new function in town - thread::sleep_ms:

use std::thread;

fn main() {
    thread::sleep_ms(4000);
}