Reputation: 3141
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);
Upvotes: 59
Views: 47244
Reputation: 432039
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.
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);
}
Upvotes: 91
Reputation: 3141
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.
Upvotes: 22