bntp

package module
v0.1.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 24, 2025 License: BSD-2-Clause Imports: 11 Imported by: 11

README

中文

BNTP - Go NTP Network Time Synchronization Library

BNTP is a high-performance Go NTP (Network Time Protocol) client library for obtaining and synchronizing network standard time.

✨ Features

  • 🌍 Multi-Region Support: Built-in NTP servers for Mainland China, Hong Kong, Taiwan, Japan, South Korea, Singapore, and global regions
  • ⚡ High Performance: Uses atomic operations and caching mechanisms to provide millisecond-level timestamp retrieval
  • 💾 Persistence: Automatically saves time offset to local file for quick recovery after restart
  • 🔄 Auto Sync: Supports periodic automatic time offset refresh (optional)

📦 Installation

go get github.com/banbox/bntp

🚀 Usage Examples

Basic Usage
package main

import (
    "log"
    "time"
    "github.com/banbox/bntp"
)

func main() {
    // LangGlobal, LangZhCN, LangZhHK, LangZhTW, LangJaJP, LangKoKr, LangZhSg, LangNone(disabled, default)
    bntp.LangCode = bntp.LangGlobal

    // Get current system time
    sysNow := time.Now()
    log.Printf("Current system time: %s\n", sysNow.Format(time.RFC3339))

    // Get corrected current time
    now := bntp.Now()
    log.Printf("Current standard time: %s\n", now.Format(time.RFC3339))

    // Get corrected timestamp (milliseconds)
    timestamp := bntp.UTCStamp()
    log.Printf("Current timestamp: %d\n", timestamp)

    // Get time offset (milliseconds)
    offset := bntp.GetTimeOffset()
    log.Printf("Time offset: %d ms\n", offset)
}
Custom Configuration
package main

import (
    "log"
    "time"
    "github.com/banbox/bntp"
)

func main() {
    _, err := bntp.SetTimeSync(
        // Set country/region code
        bntp.WithCountryCode(bntp.LangJaJP),
        
        // Set offset file save path (defaults to user cache directory)
        // bntp.WithFilePath("/path/to/ntp_offset.json"),
        
        // Enable loop refresh
        bntp.WithLoopRefresh(true),
        
        // Set sync period (recommended >= 1 hour)
        bntp.WithSyncPeriod(6 * time.Hour),
        
        // Set random fluctuation rate (between 0-1)
        bntp.WithRandomRate(0.15),
    )
    if err != nil {
        log.Fatal(err)
    }

    // Manually refresh time offset
    ts := bntp.GetTimeSync()
    if err := ts.Refresh(); err != nil {
        log.Printf("Refresh failed: %v\n", err)
    }
    
    // Get corrected timestamp (milliseconds)
    timestamp := bntp.UTCStamp()
    log.Printf("Current timestamp: %d\n", timestamp)
}

📄 License

This project is licensed under the BSD-2 License. See the LICENSE file for details.

Documentation

Index

Constants

View Source
const (
	LangNone   = "none"
	LangZhCN   = "zh-CN"
	LangZhHK   = "zh-HK"
	LangZhTW   = "zh-TW"
	LangJaJP   = "ja-JP"
	LangKoKr   = "ko-KR"
	LangZhSg   = "zh-SG"
	LangGlobal = "global"
)

Variables

View Source
var (

	// 默认时区
	LangCode = LangNone
)

原子缓存,用于快速获取时间戳

Functions

func ClearTimeSync

func ClearTimeSync()

func GetCacheDir

func GetCacheDir() (string, error)

func GetTimeOffset

func GetTimeOffset() int64

GetTimeOffset get time offset in milliseconds(>0 means local < standard)

func Now

func Now() time.Time

func SetCacheValidDuration

func SetCacheValidDuration(duration time.Duration)

SetCacheValidDuration 设置缓存有效期

func UTCStamp

func UTCStamp() int64

UTCStamp 获取校正后的UTC时间戳(毫秒)

Types

type OffsetRecord

type OffsetRecord struct {
	Timestamp int64 `json:"timestamp"` // 记录时间
	Offset    int64 `json:"offset"`    // 时间偏移(毫秒)
}

偏移记录结构

type Option

type Option func(*TimeSync)

Option 定义TimeSync的配置选项

func WithCountryCode

func WithCountryCode(code string) Option

WithCountryCode 设置国家代码

func WithFilePath

func WithFilePath(path string) Option

WithFilePath 设置偏移文件路径

func WithLoopRefresh

func WithLoopRefresh(enable bool) Option

WithLoopRefresh 启用定期刷新

func WithRandomRate

func WithRandomRate(rate float64) Option

WithRandomRate 设置同步周期的随机波动率

func WithSyncPeriod

func WithSyncPeriod(period time.Duration) Option

WithSyncPeriod 设置同步周期

type TimeSync

type TimeSync struct {
	// contains filtered or unexported fields
}

TimeSync 时间同步管理器

func GetTimeSync

func GetTimeSync() *TimeSync

GetTimeSync 获取时间同步器实例 如果实例不存在,则创建一个默认配置的实例

func SetTimeSync

func SetTimeSync(options ...Option) (*TimeSync, error)

SetTimeSync init timeSyncer, call `ClearTimeSync` if reset is need

func (*TimeSync) Close

func (ts *TimeSync) Close()

func (*TimeSync) Refresh

func (ts *TimeSync) Refresh() error

Refresh 刷新时间偏移并保存

func (*TimeSync) SetOptions

func (ts *TimeSync) SetOptions(options ...Option) error

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL