#mio #timerfd #rustix #system #timerfd-mio

timerfd-mio

Timerfd implementation for mio using rustix

1 unstable release

Uses new Rust 2024

new 0.1.0 Apr 14, 2025

#5 in #rustix

MIT license

17KB
315 lines

timerfd-mio: A High-Precision Timer for Unix Systems

timerfd-mio is a Rust crate designed to provide a safe and ergonomic interface for managing high-precision timers on Unix systems. It leverages rustix for system-level operations and integrates seamlessly with mio for non-blocking I/O event polling.

Features

  • High-precision timers using the timerfd interface.
  • Safe and ergonomic Rust API.
  • Seamless integration with mio for non-blocking I/O.
  • Support for both one-shot and periodic timers.

Usage

Here's a quick example of how to use TimerFd:

use std::time::Duration;

fn main() {
    let mut poll = mio::Poll::new().unwrap();
    let mut events = mio::Events::with_capacity(2);

    /* Timer */
    let mut timer1 = timerfd_mio::TimerFd::new().unwrap();
    timer1.set_timeout_interval(Duration::from_millis(600), Duration::from_millis(300)).unwrap();
    poll.registry().register(&mut timer1, mio::Token(1), mio::Interest::READABLE).unwrap();

    let mut timer2 = timerfd_mio::TimerFd::new().unwrap();
    timer2.set_timeout_interval(Duration::from_millis(1000), Duration::from_millis(1000)).unwrap();
    poll.registry().register(&mut timer2, mio::Token(2), mio::Interest::READABLE).unwrap();

    loop {
        poll.poll(&mut events, None).unwrap();

        for event in &events {
            if event.token() == mio::Token(1) {
                timer1.read().unwrap();
                println!("Timer 1 event");
            }
            if event.token() == mio::Token(2) {
                // this function check timer overrun
                timer2.read_and_check_overrun().unwrap();
                println!("Timer 2 event");
            }
        }
    }
}

License

This project is licensed under the MIT License. See the LICENSE file for details.

Dependencies

~2–11MB
~140K SLoC