Struct std::time::Duration は、期間を扱う型です。Function std::thread::sleep など時間を扱う関数などがこの型を期待します。
::new
では秒とミリ秒を同時に設定できます。以下ではthread::sleep(Duration::new(1, 10))
で1010ミリ秒を取得してます。
use std::thread;
use std::time::Duration;
let handler = thread::spawn(|| {
thread::sleep(Duration::new(1, 10));
println!("called");
});
handler.join().unwrap();
上記は以下のように書き換えることもできます。
::from_secs
で秒::from_millis
でミリ秒
をそれぞれ取得してます。また、Duration
はAdd
やSub
などのトレイトを実装している為+
や-
などで計算することができます。
use std::thread;
use std::time::Duration;
let handler = thread::spawn(|| {
thread::sleep(Duration::from_secs(1) + Duration::from_millis(10));
println!("called");
});
handler.join().unwrap();