ztimer
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 aClock
. It holds a callback that gets invoked upon expiration and can be canceled.AutoDropTimer
: A wrapper aroundTimer
that cancels the timer automatically when dropped, preventing further callback invocations.Clock
: Groups and manages timers. AClock
can hold several timers, and you can have multipleClock
instances in a process.
Usage
Example: Using AutoDropTimer
Here’s an example of how to use AutoDropTimer
to manage timers in your application:
use sleep;
use Duration;
use ;
// Create a clock instance
let clock = new.unwrap;
// Create some timers
let t1 = new.unwrap;
let t2 = new.unwrap;
// Use sleep to simulate the passage of time
sleep; // T1 expires
assert_eq!;
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 Clock;
// Create a clock instance
let _ = new;
// Before terminating:
let tjh = take_thread_handle;
terminate_for_process_exit;
let _ = tjh.unwrap.join;
License
This crate is licensed under the Apache License, Version 2.0. See LICENSE for details.