ntp-timer 0.1.0

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

🕐 一个轻量级、可配置的 Rust NTP 时间同步库。

## 特性

- **NTP 时间同步**:从多个 NTP 服务器获取精准时间戳
-**内存缓存**<0.1ms 的快速本地计算
-**时钟跳跃检测**:自动检测系统时钟异常调整
-**后台定期校准**:异步任务定期同步,不阻塞主线程
-**参数化配置**:所有关键参数可配置(同步间隔、跳跃阈值等)
-**线程安全**:使用 Arc<Mutex> 支持并发访问
-**完整的错误处理**:自定义 TimerError 类型

## 快速开始

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

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    // 创建配置
    let config = Config::default()
        .with_sync_interval(600)   // 每 10 分钟同步一次
        .with_jump_threshold(5);    // 时钟跳跃阈值 5 秒

    // 初始化计时器
    TimerManager::init_global_timer(Arc::new(config)).await?;

    // 获取时间戳
    let timestamp = TimerManager::get_timestamp()?;
    println!("当前时间戳: {}", timestamp);

    // 手动同步 NTP
    let synced_ts = TimerManager::manual_sync().await?;
    println!("同步后的时间戳: {}", synced_ts);

    Ok(())
}
```

## 配置参数

| 参数 | 默认值 | 说明 |
|------|--------|------|
| `sync_interval_secs` | 600 | 后台同步间隔(秒) |
| `clock_jump_threshold_secs` | 5 | 时钟跳跃检测阈值(秒) |
| `ntp_servers` | `[ntp.ntsc.ac.cn, ...]` | NTP 服务器列表 |
| `max_retries` | 3 | 最大重试次数 |
| `socket_timeout_secs` | 5 | 套接字超时(秒) |

## API 文档

### `TimerManager::init_global_timer(config)`

初始化全局计时器。首次调用时从 NTP 获取时间戳,然后启动后台同步任务。

### `TimerManager::get_timestamp()`

获取当前时间戳(快速路径,<0.1ms)。

### `TimerManager::manual_sync()`

手动触发 NTP 同步,返回最新的时间戳。

## 架构

```
TimerManager(公开API)
├── GlobalTimer(核心数据结构)
│   ├── base_timestamp(NTP 初始时间)
│   ├── base_instant(系统时钟基准点)
│   └── last_sync_at(最后同步时间)
├── Config(参数化配置)
└── NTP Module(NTP 协议实现)
```

## 设计要点

### 快速路径

```
get_timestamp() 调用 99.9% 的时间内完成 <0.1ms
    = base_timestamp + (Instant::now() - base_instant).as_secs()
```

### 时钟跳跃检测

```
每次同步时检测:|new_ntp_timestamp - current_estimate| > threshold
    - 超过阈值 → 重新初始化计时器
    - 否则 → 平滑更新基准值(纠正漂移)
```

### 后台同步

```
异步任务每 sync_interval_secs 秒运行一次
    - 不阻塞主线程
    - 失败时继续使用本地计时器
    - 自动检测并恢复时钟跳跃
```

## 性能指标

| 操作 | 耗时 | 说明 |
|------|------|------|
| `get_timestamp()` | <0.1ms | 快速路径(纯本地计算) |
| `init_global_timer()` | 50-100ms | 首次初始化(NTP 请求) |
| `manual_sync()` | 50-100ms | 手动同步(NTP 请求) |
| NTP 同步频率 | 1/10min | 后台任务 |

## 测试

```bash
cargo test --lib           # 运行单元测试
cargo test --doc           # 运行文档示例
cargo test -- --ignored    # 运行集成测试
```

## 许可证

MIT

## 贡献

欢迎提交 Issue 和 Pull Request!