简介
系统时间同步。
背景
服务器长期运行后系统时间与网络时间偏差问题。
教程
系统:Linux(CentOS7.6)
一、 设置时区
1、设置时区
# 查看时区,如果已是上海时区可不用设置
timedatectl status | grep 'Time zone'
# 设置硬件时钟调整为与本地时钟一致
timedatectl set-local-rtc 1
# 设置时区为上海
timedatectl set-timezone Asia/Shanghai
2.1、使用ntpdate同步时间(ntpdate服务需要使用udp/123端口,但是某些服务商禁止了所有UDP协议,所以你会发现无论如何ntpdate总是同步出错。可以换一种方式进行同步)
# 安装ntpdate
yum -y install ntpdate
# 同步时间 NTP服务器(上海) :ntp.api.bz
#ntpdate -u ntp.api.bz
ntpdate pool.ntp.org
# 同步完成后,date命令查看时间是否正确
date
2.2、使用rdate同步时间
# 安装rdate
yum -y install rdate
# 同步时间
rdate -s time-b.nist.gov
# 查看时间是否正确
date
3、添加定时任务同步时间
# 使用which命令来找到ntpdate的绝对路径(下面设置定时任务使用)
which ntpdate
# 安装crontab
yum -y install crontab
# 创建crontab任务
crontab -e
# 添加定时任务,每10分钟进行一次时间同步, /usr/sbin/ntpdate为ntpdate的绝对路径
# 分 时 天 月 周 命令(前面补0)
# 例如: */1 * * * * 每分钟定时执行
# 0 */1 * * * 每小时定时执行
# 30 10 * * * 每天10点30定时执行
# 0 10 * * 1 每周一10点定时执行
# 0 20 8 8 * 每年8月8日20点定时执行
10 * * * * /usr/sbin/ntpdate pool.ntp.org > /dev/null 2>&1
# 保存后退出,重启crontab
service crond reload
其他
问题记录
问题1:
ntpdate -u ntp.api.bz报错: Exiting, name server cannot be used: Temporary failure in name resolution (-3) 8 Aug 09:30:24 ntpdate[19820]: name server cannot be used: Temporary failure in name resolution (-3)
原因:nameserver设置错误
解决: vi /etc/resolv.conf
nameserver 网关地址 / nameserver 8.8.8.8 /nameserver 114.114.114.114