smol/examples/linux-timerfd.rs

45 lines
1.1 KiB
Rust
Raw Normal View History

2020-04-26 17:37:29 +00:00
//! Uses the `timerfd` crate to sleep using an OS timer.
//!
//! Run with:
//!
//! ```
//! cargo run --example linux-timerfd
//! ```
2020-03-31 16:04:16 +00:00
#[cfg(target_os = "linux")]
fn main() -> std::io::Result<()> {
use std::time::{Duration, Instant};
2020-07-23 10:24:16 +00:00
use smol::{io, Async};
2020-03-31 16:04:16 +00:00
use timerfd::{SetTimeFlags, TimerFd, TimerState};
2020-04-26 17:37:29 +00:00
/// Sleeps using an OS timer.
2020-03-31 16:04:16 +00:00
async fn sleep(dur: Duration) -> io::Result<()> {
2020-04-26 17:37:29 +00:00
// Create an OS timer.
2020-03-31 16:04:16 +00:00
let mut timer = TimerFd::new()?;
timer.set_state(TimerState::Oneshot(dur), SetTimeFlags::Default);
2020-04-26 17:37:29 +00:00
// When the OS timer fires, a 64-bit integer can be read from it.
2020-03-31 16:04:16 +00:00
Async::new(timer)?
2023-08-29 16:47:25 +00:00
.read_with(|t| rustix::io::read(t, &mut [0u8; 8]).map_err(io::Error::from))
2020-03-31 16:04:16 +00:00
.await?;
Ok(())
}
2020-08-26 21:59:49 +00:00
smol::block_on(async {
2020-03-31 16:04:16 +00:00
let start = Instant::now();
println!("Sleeping...");
2020-04-26 17:37:29 +00:00
// Sleep for a second using an OS timer.
2020-03-31 16:04:16 +00:00
sleep(Duration::from_secs(1)).await?;
2020-04-26 17:37:29 +00:00
2020-03-31 16:04:16 +00:00
println!("Woke up after {:?}", start.elapsed());
Ok(())
})
}
#[cfg(not(target_os = "linux"))]
fn main() {
println!("This example works only on Linux!");
}