Rust中程序休眠的几种方式


在rust中休眠3秒的方法有以下几种:

  1. 使用 std::thread::sleep 方法:
1
2
3
use std::thread;

thread::sleep(std::time::Duration::from_secs(3));

1
2
3
4
5
6
7
use std::thread; 
use std::time::Duration;

fn main() {
let duration = Duration::from_secs(3);
thread::sleep(duration);
}
  1. 使用 async/await语法:
1
2
3
4
5
use std::time::Duration;

async fn sleep_for_3_secs() {
tokio::time::sleep(Duration::from_secs(3)).await
}
  1. 使用时库 time::Duration:
1
2
3
4
5
use std::time::Duration;

fn main() {
thread::sleep(Duration::from_secs(3));
}
  1. 使用标准库的时间功能:
1
2
3
4
5
use std::thread;
use std::time::{Instant, Duration};

let now = Instant::now();
while now.elapsed() < Duration::from_secs(3) {}

其中:

  • std::thread::sleep 是最简单直接的方法
  • async/await用法需要异步上下文
  • Duration提供时间间隔表示
  • Instant可以获取当前时间并计算间隔

所以一般直接使用std::thread::sleep(Duration::from_secs(3))即可实现rust中3秒的休眠效果。

文章目录