测试对时偏差
使用 ntpdate -d
选项, 挑选一个合适的ntp对时地址比如 ntp.tencent.com 或者 time.pool.aliyun.com
使用 /usr/sbin/ntpdate -d ntp.tencent.com
, 可以看到如下结果, 其中offset 就代表NTP服务器时间-
系统时间, 所以offset +0.012036 sec
就代表系统时间比NTP服务器时间快了0.012036秒
menhaojie@net0:~$ /usr/sbin/ntpdate -d ntp.tencent.com
10 Jun 14:37:29 ntpdate[3259546]: ntpdate 4.2.8p15@1.3728-o Wed Feb 16 17:13:02 UTC 2022 (1)
Looking for host ntp.tencent.com and service ntp
host found : 119.28.230.190
transmit(119.28.230.190)
receive(119.28.230.190)
transmit(119.28.230.190)
receive(119.28.230.190)
transmit(119.28.230.190)
receive(119.28.230.190)
transmit(119.28.230.190)server 119.28.230.190, port 123
stratum 2, precision -23, leap 00, trust 000
refid [100.122.36.196], root delay 0.000076, root dispersion 0.026993
reference time: ea111aec.3e16edf6 Mon, Jun 10 2024 14:25:48.242
originate timestamp: ea111dad.6eab24a3 Mon, Jun 10 2024 14:37:33.432
transmit timestamp: ea111daf.66842a29 Mon, Jun 10 2024 14:37:35.400
filter delay: 0.06584 0.06573 0.06584 0.00000---- ---- ---- ----
filter offset: +0.012569 +0.012036 +0.011662 +0.000000---- ---- ---- ----
delay 0.06573, dispersion 8.00035, offset +0.01203610 Jun 14:37:37 ntpdate[3259546]: adjust time server 119.28.230.190 offset +0.012036 sec
单次对时调整
在root下运行
/usr/sbin/ntpdate time.pool.aliyun.com && /sbin/hwclock -w
接着将时区固定为国内时区, 否则将有可能按照UTC时间执行job, 那样则会出现严重的启动错误
rm -f /etc/localtime && ln -s /usr/share/zoneinfo/PRC /etc/localtime
并且修改完后必须重启cron, 否则已经设置的任务时间将还是会按照原来的UTC时间执行
systemctl restart cron # 'crond' in centos
需要注意, 如果 offset > 500ms , 更改系统时间可能会对系统和应用程序产生重要影响, 因此需要谨慎使用
Time adjustments are made by ntpdate in one of two ways. If ntpdate determines the clock is in error more than 0.5 second it will simply step the time by calling the system settimeofday() routine. If the error is less than 0.5 seconds, it will slew the time by calling the system adjtime() routine. The latter technique is less disruptive and more accurate when the error is small, and works quite well when ntpdate is run by cron every hour or two.
centos下的持续对时
运行 vi etc/chrony.conf
, 修改其中的server后指定的对时服务器地址, 注意保留后面的iburst
systemctl restart chronyd.service
systemctl enable chronyd.service
chronyc sources #查看同步状态
ubuntu下的持续对时
没有安装systemd-timesyncd的话需要先安装
apt install systemd-timesyncd
systemctl enable --now systemd-timesyncd
timedatectl timesync-status
修改 vi /etc/systemd/timesyncd.conf
, 添加 NTP=对时服务器地址
systemctl restart systemd-timesyncd
timedatectl timesync-status #查看同步状态
systemctl restart cron