MiniTimer
MiniTimer is a lightweight timer library built on the Tokio runtime, designed for scheduling and executing delayed tasks. It uses a three-level timing wheel (second wheel, minute wheel, hour wheel) algorithm to achieve O(1) time complexity for task lookup and execution.
Features
- High-performance timing wheel algorithm: Three-level timing wheel design with O(1) time complexity for task lookup and execution
- Multiple task execution modes:
- One-time delayed tasks
- Repeated tasks
- Countdown tasks (execute a fixed number of times)
- Task concurrency control: Supports setting maximum concurrency for each task
- Dynamic task management: Supports dynamically adding, canceling, and removing tasks at runtime
- Fully async: Built on Tokio runtime with async/await support
Installation
Add the dependency to your Cargo.toml:
[]
= "0.1"
= { = "1", = ["full"] }
= "0.1"
Quick Start
use async_trait;
use ;
async
Task Execution Modes
One-time Delayed Task
let task = new
.with_frequency_once_by_seconds
.spwan_async
.unwrap;
Repeated Task
let task = new
.with_frequency_repeated_by_seconds
.spwan_async
.unwrap;
Countdown Task
let task = new
.with_frequency_count_down_by_seconds
.spwan_async
.unwrap;
Timestamp-based Task
let target_timestamp = 1700000000;
let task = new
.with_frequency_once_by_timestamp_seconds
.spwan_async
.unwrap;
Concurrency Control
let task = new
.with_frequency_repeated_by_seconds
.with_max_concurrency
.spwan_async
.unwrap;
Task Management API
let timer = new;
// Add a task
timer.add_task.unwrap;
// Remove a task
let removed = timer.remove_task;
// Check if a task exists
if timer.contains_task
// Get task state
if let Some = timer.get_task_state
// Get pending tasks
let pending = timer.get_pending_tasks;
// Get running tasks
let running = timer.get_running_tasks;
// Get task count
let count = timer.task_count;
// Stop the timer
timer.stop.await;
Timing Wheel Algorithm
MiniTimer uses a three-level timing wheel for efficient task scheduling:
- Second wheel: 60 slots (0-59 seconds)
- Minute wheel: 60 slots (0-59 minutes)
- Hour wheel: 24 slots (0-23 hours)
Tasks are distributed across these wheels based on their execution time. As the wheel rotates, tasks cascade down (from hour wheel to minute wheel, from minute wheel to second wheel) until they reach the second wheel for execution. This design ensures O(1) time complexity for task lookup and execution.
Examples
More examples are available in the examples directory:
once_delayed_task.rs- One-time delayed taskrepeated_task.rs- Repeated taskcountdown_task.rs- Countdown taskconcurrency_control.rs- Concurrency controltask_management.rs- Task management
Run an example:
License
Apache-2.0