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 thethreadmodule from thestdlibraryuse std::time::Duration;- imports theDurationtype from thestd::timemodulethread::sleep(Duration::from_secs(5));- calls thesleepfunction from thethreadmodule, passing aDurationcreated 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 to match a double quote in Rust?
- How to create a HashMap of structs in Rust?
- How to replace a capture group using Rust regex?
- How to match the end of a line in a Rust regex?
- How to modify an existing entry in a Rust HashMap?
- How do I identify unused variables in Rust?
- How to use negation in Rust regex?
- Regex example to match multiline string in Rust?
- How to use a Rust HashMap in a struct?
- How do I use a variable number of arguments in Rust?
See more codes...