Expand description
§tokio-debouncer
A lightweight, cancel-safe async debouncer for Tokio tasks.
§Overview
This crate provides a simple, robust, and deterministic debouncer for batching signals or jobs in async workflows. It is especially suited for job queues, event batching, and select-based async workers where you want to coalesce bursts of work and process them efficiently.
- Supports both leading and trailing debounce modes.
- Designed for use with
tokio::select!for robust, cancel-safe batching. - Can be triggered from any thread or task.
- Fully tested with simulated time.
§Example
use tokio_debouncer::{Debouncer, DebounceMode};
use tokio::time::Duration;
#[tokio::main]
async fn main() {
// Create a debouncer with a 100ms cooldown in trailing mode
let debouncer = Debouncer::new(Duration::from_millis(100), DebounceMode::Trailing);
debouncer.trigger(); // Signal an event
let _guard = debouncer.ready().await; // Wait until ready; debounce is finalized on drop
// Do your work here
}§Select-based Job Queue Example
use tokio::{select, time::{sleep, Duration}};
use tokio_debouncer::{Debouncer, DebounceMode};
#[tokio::main]
async fn main() {
let debouncer = Debouncer::new(Duration::from_secs(1), DebounceMode::Trailing);
let debouncer2 = debouncer.clone();
tokio::spawn(async move {
loop {
debouncer2.trigger();
sleep(Duration::from_millis(200)).await;
}
});
let mut iterations = 10;
loop {
iterations -= 1;
if iterations == 0 {
break;
}
// Wait for the debouncer to be ready
select! {
_guard = debouncer.ready() => {
// Debounce is finalized automatically on drop
println!("Processing job batch!");
}
_ = sleep(Duration::from_millis(100)) => {
// Handle other events
}
}
}
}§Best Practice
The debounce state is now finalized automatically when the guard is dropped. You do not need to call any method to commit the debounce; simply let the guard go out of scope after acquiring it. This ensures robust, cancellation-safe batching, even if your task is cancelled or panics after acquiring the guard.
If you need to do work after acquiring the guard, do it after awaiting ready() and let the guard drop naturally.
Structs§
- Debouncer
- Debouncer struct for batching events or jobs. Can be cloned and shared between tasks.
- Debouncer
Guard - Guard returned by Debouncer::ready().
Enums§
- Debounce
Mode - The debounce mode: Leading or Trailing.
Traits§
Type Aliases§
- Mutex
- A mutual exclusion primitive useful for protecting shared data
- Mutex
Guard - An RAII implementation of a “scoped lock” of a mutex. When this structure is dropped (falls out of scope), the lock will be unlocked.