rustHow to delay a thread in Rust?
Threads can be delayed in Rust using the std::thread::sleep
function. This function takes a std::time::Duration
as an argument, which can be created from a number of seconds.
use std::thread;
use std::time::Duration;
fn main() {
thread::sleep(Duration::from_secs(5));
println!("5 seconds have passed");
}
Output example
5 seconds have passed
The code above will delay the thread for 5 seconds before printing the message.
Code explanation
use std::thread;
- imports thethread
module from thestd
libraryuse std::time::Duration;
- imports theDuration
type from thestd::time
modulethread::sleep(Duration::from_secs(5));
- calls thesleep
function from thethread
module, passing aDuration
created from 5 secondsprintln!("5 seconds have passed");
- prints the message after the thread has been delayed
Helpful links
More of Rust
- How to use regex with bytes in Rust?
- How to split a string with Rust regex?
- How to replace all using regex in Rust?
- How to use regex to match a double quote in Rust?
- How to replace all matches using Rust regex?
- How to replace strings using Rust regex?
- How to get a capture group using Rust regex?
- How to perform matrix operations in Rust?
- How to convert a Rust HashMap to a BTreeMap?
- How to use Unicode in a regex in Rust?
See more codes...