centos7 时区同步

查看服务器使用的时间类型

[root@yfm08 ~]# timedatectl status
      Local time: Sat 2021-02-27 01:49:47 CST
  Universal time: Fri 2021-02-26 17:49:47 UTC
        RTC time: Fri 2021-02-26 17:49:47
       Time zone: Asia/Shanghai (CST, +0800)
     NTP enabled: n/a
NTP synchronized: no
 RTC in local TZ: no
      DST active: n/a

我们可以看到,服务器使用的CST 时间,将服务器时间类型改为UTC

timedatectl  set-timezone UTC

将系统时间写入硬件CMOS

看CMOS的时间
clock -r 

将当前系统时间写入CMOS中去  
clock  -w

显示UTC时间
date   -u

 ln -sf /usr/share/zoneinfo/Asia/Shanghai    /etc/localtime

使用ntpdate同步时间

#安装ntpdate
yum -y install ntpdate
#同步时间
ntpdate -u  ntp2.aliyun.com
#同步完成后,date命令查看时间是否正确
date "+%Y-%m-%d %H:%M:%S"

同步时间后可能部分服务器过一段时间又会出现偏差,因此最好设置crontab来定时同步时间,方法如下:

#安装crontab
yum -y install crontab
#创建crontab任务
crontab -e
#添加定时任务
*/20 * * * * /usr/sbin/ntpdate ntp2.aliyun.com > /dev/null 2>&1
#重启crontab
service crond reload

上面的计划任务会在每20分钟进行一次时间同步,注意/usr/sbin/ntpdate为ntpdate命令所在的绝对路径,不同的服务器可能路径不一样,可以使用which命令来找到绝对路径,方法如下:

[root@yfm06 ~]# which ntpdate
/usr/sbin/ntpdate

参考:

CentOS 7同步时间的2种方法

CentOS 7 - 配置阿里云 NTP 服务

【UTC】CentOS7修改时区的正确姿势

猜你喜欢

转载自blog.csdn.net/yfm081616/article/details/114964883