49

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);
Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Tiago
  • 2,871
  • 4
  • 23
  • 39

2 Answers2

75

Rust 1.4+

Duration and sleep have returned and are stable!

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

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);
}
Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
18

Updated answer

This is the updated code for the current Rust version:

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

fn main() {
    sleep(Duration::from_millis(2));
}

Rust play url: http://is.gd/U7Oyip

Old answer pre-1.0

According the pull request https://github.com/rust-lang/rust/pull/23330 the feature that will replace the old std::old_io::timer::sleep is the new std::thread::sleep.

Pull request description on GitHub:

This function is the current replacement for std::old_io::timer which will soon be deprecated. This function is unstable and has its own feature gate as it does not yet have an RFC nor has it existed for very long.

Code example:

#![feature(std_misc, thread_sleep)]

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

fn main() {
    sleep(Duration::milliseconds(2));
}

This uses sleep and Duration, which are currently behind the feature gates of thread_sleep and std_misc, respectively.

Tiago
  • 2,871
  • 4
  • 23
  • 39
  • error: #[feature] may not be used on the stable release channel. A great many wonderful APIs are unlocked using #[feature] but if you download Rust from the prominent web sites you can't use #[feature]. – cardiff space man Oct 29 '15 at 22:37