问题
给公司架设了一个学习网站Moodle,但经常发现系统时间不对。影响统计。通过ntpdate和crontab等若干步骤,搞定。
思路
起初找了一些博文提供的ntp server,都没有成功同步,后来找到一个可以同步的服务器 ntpdate 129.6.15.28
有时候你会发现date显示的时间是时区0的时间,存在时差。可以通过运行命令tzselect然后输入选项前面的数字来一步一步地设置当前系统时区。再将TZ=‘Asia/Shanghai’; export TZ这行添加到/etc/profile(所有用户生效)或者~/.bash_profile(当前用户生效)。退出重新登录即可,也可执行source /etc/profile或source ~/.bash_profile立即生效。再执行date查看日期就可以发现时区改为北京时间了。
最后,还需要检查系统硬件时间,如果错误,执行 hwclock --systohc
优化
考虑到定期同步的重要性,决定使用crontab 服务
1,44 * * * * /usr/sbin/ntpdate 129.6.15.28
当然 这里的命令写上去路径,否则执行失败。关于语法就省略了(每小时的第一分钟和第44分钟自动执行)
systemctl enable crond
systemctl start crond
检查
为了第一时间检查是否执行成功,检查cron log 文件,确认完毕。
tail -f /var/log/cron
[root@localhost ~]# cat /var/log/cron | grep ntpdate
Apr 11 17:42:01 localhost CROND[12108]: (root) CMD (ntpdate 129.6.15.28)
Apr 11 17:42:01 localhost CROND[12106]: (root) CMDOUT (/bin/sh: ntpdate: command not found)
Apr 11 17:44:01 localhost CROND[12144]: (root) CMD (/usr/sbin/ntpdate 129.6.15.28)
Apr 11 17:44:08 localhost CROND[12142]: (root) CMDOUT (11 Apr 17:44:08 ntpdate[12144]: adjust time server 129.6.15.28 offset -0.017346 sec)
Apr 11 18:01:01 localhost CROND[12179]: (root) CMD (/usr/sbin/ntpdate 129.6.15.28)
Apr 11 18:01:08 localhost CROND[12176]: (root) CMDOUT (11 Apr 18:01:08 ntpdate[12179]: adjust time server 129.6.15.28 offset -0.006660 sec)
Apr 11 18:44:01 localhost CROND[12237]: (root) CMD (/usr/sbin/ntpdate 129.6.15.28)
Apr 11 18:44:08 localhost CROND[12235]: (root) CMDOUT (11 Apr 18:44:08 ntpdate[12237]: adjust time server 129.6.15.28 offset 0.004221 sec)
Apr 11 19:01:01 localhost CROND[12263]: (root) CMD (/usr/sbin/ntpdate 129.6.15.28)
Apr 11 19:01:08 localhost CROND[12259]: (root) CMDOUT (11 Apr 19:01:08 ntpdate[12263]: adjust time server 129.6.15.28 offset -0.002979 sec)
Apr 11 19:44:01 localhost CROND[12319]: (root) CMD (/usr/sbin/ntpdate 129.6.15.28)
Apr 11 19:44:08 localhost CROND[12317]: (root) CMDOUT (11 Apr 19:44:08 ntpdate[12319]: adjust time server 129.6.15.28 offset -0.007664 sec)
Apr 11 20:01:01 localhost CROND[12359]: (root) CMD (/usr/sbin/ntpdate 129.6.15.28)
Apr 11 20:01:08 localhost CROND[12355]: (root) CMDOUT (11 Apr 20:01:08 ntpdate[12359]: adjust time server 129.6.15.28 offset -0.009397 sec
)