Linux下自动同步系统时间

来源:互联网 发布:mysql缓存机制 编辑:程序博客网 时间:2024/04/26 10:22

在discuzx2.5 绑定qq的时候老是报网络错误,但是域名那些解析或者ping都能通,后来查过网络发现是系统时间问题.

linux 同步时间后,搞定,但是第二天在用qq登录的时候发现又包同样的错误.用date命令查看.又跟电脑时间晚了很多分钟...

于是就搞了下面这个shell脚本实现时间自动同步.

首先需要设置一台局域网的NTP时间服务器 这里用的是pool.ntp.org

在root目录先创建个 updatetime.sh

vi /root/updatetime.sh

同步脚本为

#!/bin/sh
server="pool.ntp.org"
/usr/sbin/ntpdate -s $server
/usr/sbin/hwclock --systohc
exit

保存为updatetime.sh (我以前保存为ntpdate.sh,一直报错,找了好几天才发现这个错,哎,不应该啊)

然后加入执行权限

chmod 755 updatetime.sh

下面加入计划任务,每天0点0分执行校对

[root@121 ~]# crontab -u root -e
5分钟同步一次时间


* /5  *  *  *  *  sh /root/updatetime.sh 

 

查看该计划任务:crontab -l
重启crond任务:/etc/rc.d/init.d/crond restart或者service crond restart

附:

把当前的时间写入硬件:#hwclock --systohc

强制把linux系统中时间写入CMOS :#clock -w

注:以前发现手工执行脚本可以同步时间,但是放到crontab里面就执行不了,后来看到日志

You have mail in /var/spool/mail/root 下面

/root/updatetime.sh :line 3:ntpdate :command not found

发现是找不到ntpdate这个命令,后来改成

/usr/sbin/ntpdate -s $server

才成功执行,要写出ntpdate的绝对路径

原创粉丝点击