A minimal naive timer for embedded platforms in Rust (no_std + alloc).
NOTE: We need to use a nightly version of Rust.
The naive-timer
is really naive, that it only has 30 lines of code.
```rust use alloc::boxed::Box; use alloc::collections::BTreeMap; use core::time::Duration;
/// A naive timer.
pub struct Timer {
events: BTreeMap
/// The type of callback function.
type Callback = Box
impl Timer {
/// Add a timer.
///
/// The callback
will be called on timer expired after deadline
.
pub fn add(
&mut self,
mut deadline: Duration,
callback: impl FnOnce(Duration) + Send + Sync + 'static,
) {
while self.events.containskey(&deadline) {
deadline += Duration::fromnanos(1);
}
self.events.insert(deadline, Box::new(callback));
}
/// Expire timers.
///
/// Given the current time `now`, trigger and remove all expired timers.
pub fn expire(&mut self, now: Duration) {
while let Some(entry) = self.events.first_entry() {
if *entry.key() > now {
return;
}
let (_, callback) = entry.remove_entry();
callback(now);
}
}
} ```
That's ALL.
The code in this repository is licensed under the MIT License.