Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I put the current thread to sleep?

Tags:

sleep

rust

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); 
like image 800
Tiago Avatar asked Mar 09 '15 22:03

Tiago


People also ask

How do we stop a current running thread?

Whenever we want to stop a thread from running state by calling stop() method of Thread class in Java. This method stops the execution of a running thread and removes it from the waiting threads pool and garbage collected.

Which command makes thread sleep?

Command to make thread sleep? Explanation: A particular thread of the application can be blocked forever by calling Thread. Sleep(Timeout. Infinite).

How do I make my thread sleep for 1 minute?

To make a thread sleep for 1 minute, you do something like this: TimeUnit. MINUTES. sleep(1);

What's thread sleep () in threading?

Definition. Suspends the current thread for the specified amount of time.


1 Answers

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); } 
like image 123
Shepmaster Avatar answered Sep 23 '22 04:09

Shepmaster