Skip to main content

Crate ntp_timer

Crate ntp_timer 

Source
Expand description

§NTP Timer

A lightweight NTP time synchronization library for Rust applications. Provides in-process cached global time with automatic background synchronization and clock-jump detection.

§Features

  • NTP Time Synchronization: Fetch precise timestamps from multiple NTP servers
  • In-Memory Cache: <0.1ms fast local calculation
  • Clock Jump Detection: Automatically detect and handle system clock adjustments
  • Background Synchronization: Async periodic sync tasks that don’t block the main thread
  • Fully Configurable: All critical parameters are customizable
  • Thread-Safe: Concurrent access supported via Arc

§Quick Start

use ntp_timer::{Config, TimerManager};
use std::sync::Arc;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    // Create configuration with default values
    let config = Config::default()
        .with_sync_interval(600)      // Sync every 10 minutes
        .with_jump_threshold(5);      // Clock jump threshold: 5 seconds

    // Initialize global timer
    TimerManager::init_global_timer(Arc::new(config)).await?;

    // Get current timestamp (fast path, <0.1ms)
    let timestamp = TimerManager::get_timestamp()?;
    println!("Current timestamp: {}", timestamp);

    // Manual synchronization
    let synced_ts = TimerManager::manual_sync().await?;
    println!("Synced timestamp: {}", synced_ts);

    Ok(())
}

§Architecture

  • GlobalTimer: Core data structure holding NTP timestamp and system instant references
  • TimerManager: Public API providing global timer access (singleton pattern)
  • Config: Configurable parameters (sync interval, NTP servers, thresholds, etc.)
  • NTP Module: Low-level NTP protocol implementation

Re-exports§

pub use config::Config;
pub use error::TimerError;
pub use sync::TimerManager;
pub use timer::GlobalTimer;

Modules§

config
error
ntp
sync
timer

Type Aliases§

Result
Convenience type alias for Results in this crate