萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 作業系統 >  >> Linux 教學

Linux 時間管理精要:硬體時鐘、系統時鐘、時區與 NTP 同步

兩個時鐘:硬體時鐘 (RTC) vs 系統時鐘

  • 硬體時鐘 (RTC/CMOS clock):主機板晶振+電池,斷電仍走動,精度有限(秒級),僅儲存日期時間(無時區概念)
  • 系統時鐘 (Kernel/Software clock):核心維護的計數器(自 1970-01-01 00:00:00 UTC 起的秒數/奈秒),精度高(奈秒級),啟動時從 RTC 讀取初始化,之後獨立運作

時間基準:UTC 與本地時間

  • 核心**永遠以 UTC 運作**,不處理時區、夏令時間
  • 使用者空間透過 TZ 環境變數或 /etc/localtime 轉換顯示
  • RTC 可設為 UTC 或本地時間,**強烈建議設為 UTC** 避免夏令時間切換時需調整 RTC

時區配置

# 系統預設時區 (systemd 系統)
timedatectl set-timezone Asia/Taipei

# 傳統方式
ln -sf /usr/share/zoneinfo/Asia/Taipei /etc/localtime

# 使用者個人時區
export TZ=Asia/Taipei
# 或寫入 ~/.profile

查看與設定時間

關鍵檔案

  • /etc/localtime:時區資料檔副本/連結
  • /usr/share/zoneinfo/:時區資料庫 (tzdata 套件提供)
  • /etc/adjtime:記錄 RTC 系統時間差異與調整歷史,供 hwclock 計算漂移修正
  • /etc/timezone:部分發行版記錄時區名稱

網路時間同步 (NTP)

Chrony (現代首選,RHEL 7+/Fedora/Ubuntu 20.04+ 預設)

# 安裝
yum/dnf/apt install chrony

# 配置 /etc/chrony.conf
pool pool.ntp.org iburst
# 或指定台灣伺服器
server time.stdtime.gov.tw iburst
server tick.stdtime.gov.tw iburst
server tock.stdtime.gov.tw iburst

# 啟用
systemctl enable --now chronyd

# 狀態查看
chronyc tracking
chronyc sources -v

ntpd (傳統,逐漸淘汰)

# /etc/ntp.conf
server 0.pool.ntp.org iburst
server 1.pool.ntp.org iburst
restrict default kod nomodify notrap nopeer noquery
restrict -6 default kod nomodify notrap nopeer noquery

systemctl enable --now ntpd
ntpq -p

systemd-timesyncd (輕量 SNTP 客戶端)

# /etc/systemd/timesyncd.conf
[Time]
NTP=time.stdtime.gov.tw tick.stdtime.gov.tw
FallbackNTP=pool.ntp.org

systemctl enable --now systemd-timesyncd
timedatectl show-timesync --all

時間調整的風險與最佳實踐

  • 避免大幅跳躍:cron、資料庫、分布式鎖、日誌分析皆依賴單調時間。若需校準大偏差,啟用 chrony 的 makestep 閾值(預設 1 秒以上漸進調整,閾值內階躍)
  • 虛擬機時間漂移:啟用 hypervisor 時間同步 (VMware Tools, Hyper-V Integration Services, KVM guest agent) 或在客體運行 chrony
  • 容器時間:容器共享宿主機核心時間,不可在容器內設定時間(需 SYS_TIME capability)
  • 日誌時間戳:統一使用 UTC 儲存,展示層再轉換時區

測量檔案系統空洞 (Sparse Files) 附錄

稀疏檔案中未寫入資料的區塊不佔實體磁碟空間。工具 measure-holes.c 讀取區塊檢測全零區段,統計潛在空洞大小。現代檔案系統 (ext4, XFS, Btrfs) 原生支援稀疏檔,cp --sparse=always、tar -S、rsync -S 保留空洞特性。

結語

時間是分布式系統的心跳。統一 UTC、部署 Chrony、監控時鐘偏移 (Prometheus node_timex 指標)、拒絕手動大跳躍,是維運穩定基礎設施的鐵律。

copyright © 萬盛學電腦網 all rights reserved
操作指令說明
顯示系統時間date依時區顯示
顯示 UTC 時間date -u
設定系統時間date MMDDhhmm[[CC]YY][.ss]需 root,格式月日時分[年][.秒]
顯示硬體時鐘hwclock -r / hwclock --show
系統時間寫入硬體hwclock -w / hwclock --systohc加 --utc 指明 RTC 為 UTC
硬體時間寫入系統hwclock -s / hwclock --hctosys開機腳本自動執行