Linux系统有系统时间和硬件时间之分:
系统时间: 一般说来就是我们执行 date命令看到的时间,linux系统下所有的时间调用(除了直接访问硬件时间的命令)都是使用的这个时间。
硬件时间:主板上BIOS中的时间,由主板电池供电来维持运行,系统开机时要读取这个时间,并根据它来设定系统时间(注意:系统启动时根据硬件时间设定系统时间的过程可能存在时区换算,这要视具体的系统及相关设置而定)。
- 查看当前系统时间:
date
[root@web176 ~]# date
Fri Nov 6 14:21:29 CST 2020
- 设置系统时间:
date -s +时间
[root@web176 ~]# date -s 10:10:10
Fri Nov 6 10:10:10 CST 2020
[root@web176 ~]# date
Fri Nov 6 10:10:14 CST 2020
- 设置系统时间时,如果还需要设置日期,则要将日期与时间值用双引号包裹起来
[root@web176 ~]# date -s "2020/11/11 10:00:00"
Wed Nov 11 10:00:00 CST 2020
[root@web176 ~]# date
Wed Nov 11 10:00:02 CST 2020
- 查看硬件时间用
hwclock
或者clock
命令:
[root@web176 ~]# hwclock
Fri 06 Nov 2020 02:26:34 PM CST -0.640974 seconds
[root@web176 ~]# clock
Fri 06 Nov 2020 02:26:43 PM CST -0.969077 seconds
- 将硬件时间写入到系统时间:
hwclock -s
[root@web176 ~]# hwclock -s
[root@web176 ~]# clock
Fri 06 Nov 2020 02:27:23 PM CST -0.629706 seconds
[root@web176 ~]# date
Fri Nov 6 14:27:27 CST 2020
- 将系统时间写入到硬件时间:
hwclock -w
[root@web176 ~]# date -s "2020/11/11 10:00:00"
Wed Nov 11 10:00:00 CST 2020
[root@web176 ~]# date
Wed Nov 11 10:00:01 CST 2020
[root@web176 ~]# hwclock -w
[root@web176 ~]# clock
Wed 11 Nov 2020 10:00:20 AM CST -0.223458 seconds
[root@web176 ~]# date
Wed Nov 11 10:00:21 CST 2020
- 时间同步,Linux系统需安装ntpdate
- 检查是否安装了ntpdate:
rpm -qa | grep ntpdate
[root@web176 ~]# rpm -qa | grep ntpdate
ntpdate-4.2.6p5-15.el6.centos.x86_64
- 如果没有安装则运行如下命令:
yum install ntpdate
- 开启ntpd服务:
/etc/init.d/ntpd start
- 时间同步命令:
ntpdate www.pool.net.org
/ntpdate cn.pool.ntp.org
其中www.pool.net.org
、cn.pool.ntp.org
是互联网中标准时间服务器
[root@web176 ~]# ntpdate www.pool.net.org
11 Nov 10:05:04 ntpdate[122336]: no server suitable for synchronization found
[root@web176 ~]# ntpd start
ntpd: Command line arguments not allowed
ntpd - NTP daemon program - Ver. 4.2.6p5
USAGE: ntpd [ -<flag> [<val>] | --<name>[{=| }<val>] ]...
[root@web176 ~]# /etc/init.d/ntpd start
Starting ntpd: [ OK ]
[root@web176 ~]# ntpdate www.pool.net.org
11 Nov 10:07:05 ntpdate[122400]: the NTP socket is in use, exiting
[root@web176 ~]# /etc/init.d/ntpd stop
Shutting down ntpd: [ OK ]
[root@web176 ~]# ntpdate www.pool.net.org
6 Nov 14:35:05 ntpdate[122414]: no server suitable for synchronization found
[root@web176 ~]# ntpdate cn.pool.ntp.org
6 Nov 14:35:52 ntpdate[122436]: adjust time server 84.16.73.33 offset 0.000769 sec
[root@web176 ~]# date
Fri Nov 6 14:36:00 CST 2020
[root@web176 ~]# /etc/init.d/ntpd start
Starting ntpd: [ OK ]
- 网络时间服务器
首先得确保这些服务器都能ping通否则是无法时间同步的。否则会报错“no server suitable for synchronization found”:
[root@web176 ~]# ntpdate www.pool.net.org
11 Nov 10:05:04 ntpdate[122336]: no server suitable for synchronization found
- NTP服务器(上海) :ntp.api.bz
- 中国ntp服务器:cn.pool.ntp.org、pool.ntp.org
- 自动时间同步
- 配置开机启动校验
vim /etc/rc.d/rc.local
/usr/sbin/ntpdate -u ntp.api.bz> /dev/null 2>&1; /sbin/hwclock -w
- 配置定时任务
vim /etc/crontab
0 8 * * 6 root /usr/sbin/ntpdate pool.ntp.org > /dev/null 2>&1; /sbin/hwclock -w