#timer #applications #clock #numbers #thread #overhead #instance

ztimer

A block-based, non-circular double-linked list implementation for Rust

3 releases

0.1.2 Sep 20, 2024
0.1.1 Sep 17, 2024
0.1.0 Sep 17, 2024

#580 in Data structures

34 downloads per month

Apache-2.0

285KB
6.5K SLoC

ztimer

Crates.io Docs.rs

ztimer (Zero-Overhead Timer) provides a highly efficient, near O(1) timer system for Rust applications. It assumes that, in most use cases, the number of timer expirations is limited, eliminating the need to support a huge number of expirations, and reducing overhead.

Features

  • Efficient Timer: Implements a near O(1) timer suitable for systems that require minimal overhead.
  • Auto-Drop Timer: Automatically cancels the underlying timer if the AutoDropTimer instance is dropped before expiration.
  • Clock Management: A Clock can manage multiple timers within the same process, handling multiple timer groups based on your application needs.
  • Cancelable Timers: Timer instances can be canceled before they expire, avoiding callback invocations.
  • Thread-Safe Execution: Manages timers across threads using safe abstractions and provides support for non-blocking tick processing.

Concepts

  • Timer: A direct reference to a real timer instance stored in a Clock. It holds a callback that gets invoked upon expiration and can be canceled.
  • AutoDropTimer: A wrapper around Timer that cancels the timer automatically when dropped, preventing further callback invocations.
  • Clock: Groups and manages timers. A Clock can hold several timers, and you can have multiple Clock instances in a process.

Usage

Example: Using AutoDropTimer

Here’s an example of how to use AutoDropTimer to manage timers in your application:

use std::thread::sleep;
use std::time::Duration;
use ztimer::{AutoDropTimer, Clock};

// Create a clock instance
let clock = Clock::new(None).unwrap();

// Create some timers
let t1 = AutoDropTimer::new(clock, Duration::from_secs(1), || {
    println!("T1 expired");
}, "t1".to_string()).unwrap();

let t2 = AutoDropTimer::new(clock, Duration::from_secs(10), || {
    println!("T2 expired");
}, "t2".to_string()).unwrap();

// Use sleep to simulate the passage of time
sleep(Duration::from_secs(2)); // T1 expires
assert_eq!(clock.len(), 2);

Example: Waiting for the Underlying Timer Thread Before Termination

If your application needs to wait for the underlying timer thread before exiting, here's what you should do:

use ztimer::Clock;

// Create a clock instance
let _ = Clock::new(None);

// Before terminating:
let tjh = Clock::take_thread_handle();
Clock::terminate_for_process_exit();
let _ = tjh.unwrap().join();

License

This crate is licensed under the Apache License, Version 2.0. See LICENSE for details.

Dependencies

~1–1.8MB
~33K SLoC