HiveBrain v1.2.0
Get Started
← Back to all entries
snippetrustModerate

How can I put the current thread to sleep?

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
howthecurrentsleepcanthreadput

Problem

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);

Solution

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.

Code Snippets

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

fn main() {
    sleep(Duration::from_millis(2));
}
#![feature(std_misc, thread_sleep)]

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

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

Context

Stack Overflow Q#28952938, score: 22

Revisions (0)

No revisions yet.