zl程序教程

您现在的位置是:首页 >  系统

当前栏目

时间同步:Linux同步国家授时中心的时间

Linux同步 时间 中心 国家
2023-09-14 08:59:05 时间

Linux服务器运行久时,系统时间就会存在一定的误差,一般情况下可以使用date命令进行时间设置,但在做数据库集群分片等操作时对多台机器的时间差是有要求的,此时就需要使用ntpdate进行时间同步。

 
date命令
date -R :查看当前时间,结果如下:Thu, 04 Jun 2020 09:36:39 +0800      #  +0800 表示东八区
date -s 09:38:40 :设置当前时间,结果如下:Tue Mar 4 09:38:40 CST 2020
 
安装时间同步工具:
rpm -q ntp :检查是否已经安装了ntp工具
yum -y install ntp  如果没有安装ntp,则使用yum命令安装

 
ntpdate命令
ping ntp.api.bz  :检查时间服务器的可用性
ntpdate -u ntp.api.bz :网络时间同步命令
 
注意:若不加上-u参数, 会出现以下提示:no server suitable for synchronization found
-u:从man ntpdate中可以看出-u参数可以越过防火墙与主机同步;
ntp.api.bz:NTP(上海)的官方时间服务器。
 
ntp常用服务器
中国国家授时中心:210.72.145.44
NTP服务器(上海) :ntp.api.bz
 
美国:time.nist.gov 
复旦:ntp.fudan.edu.cn 
微软公司授时主机(美国) :time.windows.com 
台警大授时中心(台湾):asia.pool.ntp.org
 
经测试中国国家授时中心与NTP上海服务器可以正常同步时间,注意需要加上-u参数!
 
改写为自动定时更新:

1、编写被定时执行的脚本:
cd /usr/local/bin
vim ntpdate_timesync.sh # 写入如下内容。

ntpdate -u ntp.api.bz >> ntpdate.log 

 

# 与ntp.api.bz同步一次时间,输出记录到ntpdate.log。操作前,先ping ntp.api.bz 通过,否则更换时间服务器。
chmod +x ntpdate_timesync.sh
bash /usr/local/bin/ntpdate_timesync.sh # 测试脚本是否可以正常工作
cat ntpdate.log # 查看是否有日志正确输出,如:4 Jun 10:42:54 ntpdate[3767]: adjust time server 114.118.7.161 offset -0.003343 sec

2、对脚本实现定时执行管理:
yum install crontabs -y 安装定时工具crontabs
service crond status
service crond start
crontab -l # 查看定时任务清单
systemctl enable crond.service # 将定时工具设置为开机自启
crontab -l # 编辑定时工具的配置文件,写入如下内容:每天21:30自动执行一次脚本

# For details see man 4 crontabs

# Example of job definition:
# .---------------- minute (0 - 59)
# | .------------- hour (0 - 23)
# | | .---------- day of month (1 - 31)
# | | | .------- month (1 - 12) OR jan,feb,mar,apr ...
# | | | | .---- day of week (0 - 6) (Sunday=0 or 7) OR sun,mon,tue,wed,thu,fri,sat
# | | | | |
# * * * * * user-name command to be executed
30 21 * * * bash /usr/local/bin/ntpdate_timesync.sh