天天看点

Linux时间同步

版权声明:欢迎转载,请注明沉默王二原创。 https://blog.csdn.net/qing_gee/article/details/42234997

在我们的项目中,需要同步Linux服务器的时间,于是用到了ntpdate命令

1.使用crontab -l命令查看定时服务
[root@MyCloudServer xxx]# crontab -l
0,10,20,30,40,50 * * * * ntpdate time.windows.com &>/xxx/ntpdate.log      
2.看起来好像没有问题啊,vim /var/spool/mail/root(定时服务日志会存放在该文件中)查看定时服务日志,发现有如下信息
/bin/sh: ntpdate: command not found
      

说明定时服务在/bin/sh目录中去找ntpdate命令,并且没有找到

3.使用whereis ntpdate命令看看该命令在什么目录下
[root@MyCloudServer cron]# whereis ntpdate
ntpdate: /usr/sbin/ntpdate /usr/share/man/man8/ntpdate.8.gz      

问题找到了,在定时服务中,ntpdate命令要使用全路径

4.使用crontab -e命令修改一下,加上ntpdate命令的目录
0,10,20,30,40,50 * * * * /usr/sbin/ntpdate time.windows.com &>/xxx/ntpdate.log      

然而保存后,等到整数分钟后,在日志中没有发现该命令执行,为什么呢,猜想如下

a.以上命令格式错误,时间格式错误

b.cron自动服务没有执行

通过网上查找时间的命令格式,发现

0,10,20,30,40,50 * * * *      

并没有错误,而手动执行

/usr/sbin/ntpdate time.windows.com &>/xxx/ntpdate.log      

也成功执行,那么就看看b是否存在问题

5.执行ps -ef | grep cron,查看时间服务进程是否存在
[root@MyCloudServer xxx]# ps -ef | grep cron
root     26157 22992  0 10:04 pts/3    00:00:00 grep cron      

发现没有cron执行进程

6.执行service crond status查看服务状态
[root@MyCloudServer xxx]# service crond status
crond is stopped      

竟然服务没有启动,好吧

7.启动进程,并且查看状态
[root@MyCloudServer xxx]# service crond start
Starting crond:                                            [  OK  ]
[root@MyCloudServer xxx]# service crond status
crond (pid  26291) is running...
[root@MyCloudServer xxx]# ps -ef | grep cron
root     26291     1  0 10:06 ?        00:00:00 crond
root     26302 22992  0 10:06 pts/3    00:00:00 grep cron      
8.服务启动了,通过vim /etc/rc.d/rc.local命令添加以下语句设置为开机启动
/sbin/service crond start      

注意也加上了/sbin目录

9.最后再看看ntpdate.log中有没有执行日志
[root@MyCloudServer xxx]# cat ntpdate.log 
29 Dec 11:10:16 ntpdate[29960]: no server suitable for synchronization found      

发现服务器没有找到对应的服务同步,那么猜想应该是time.windows.com服务器在本台服务器上没有获取成功,由于我们用的是香港的云服务器,那么换一个香港认可的地址试试

0,10,20,30,40,50 * * * * /usr/sbin/ntpdate stdtime.gov.hk &>/xxx/ntpdate.log      

然后等到整时分钟的时候再次查看一下

[root@MyCloudServer xxx]# cat ntpdate.log 
29 Dec 11:20:01 ntpdate[30580]: adjust time server 118.143.17.82 offset 0.015206 sec      

可以看到执行成功了

总结:通过以上问题调查,发现无论什么时候经验主义并不可靠,小小的一个问题都可能引发很多原因。

继续阅读