任务要求:系统每天在21:00的时候同步时间,以保证系统时间的准确性。
脚本如下:
备注:若你的定时任务中有其他内容,请使用>>累加,而不是>覆盖!
0 1 2 3 4 5 |
[root@byrd script]# echo '#This is a time synchronization BY:BYRD AT:2014-03-31' >>/var/spool/cron/root [root@byrd script]# echo '00 21 * * * /bin/sh /byrd/script/ntpdate.sh >/dev/null 2>&1' >>/var/spool/cron/root [root@byrd script]# cat /var/spool/cron/root #This is a time synchronization BY:BYRD AT:2014-03-31 00 21 * * * /bin/sh /byrd/script/ntpdate.sh >/dev/null 2>&1 [root@byrd script]# |
以上脚本,拆分如下:
0 1 2 3 4 5 6 7 8 |
[root@byrd ~]# find / -name "ntpdate" /usr/sbin/ntpdate [root@byrd ~]# mkdir /byrd/script -p [root@byrd ~]# cd /byrd/script/ [root@byrd script]# vim ntpdate.sh [root@byrd script]# chmod 755 ntpdate.sh [root@byrd script]# ll total 4 -rwxr-xr-x. 1 root root 215 Mar 31 21:32 ntpdate.sh |
脚本内容如下:
0 1 2 3 4 5 6 7 8 |
[root@byrd script]# cat ntpdate.sh #!/bin/bash #NTPDATE #This is a time synchronization scripts #history #by:byrd 2014-03-31 PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin:/root/bin export PATH /usr/sbin/ntpdate time.windows.com |
将脚本加入定时任务中:
0 |
[root@byrd script]# crontab -e |
增加内容如下:
0 1 |
#This is a time synchronization BY:BYRD AT:2014-03-31 */1 * * * * /bin/sh /byrd/script/ntpdate.sh >/dev/null 2>&1 #备注为了测试效果,现在为每一分更新一次时间。 |
测试过程如下:
0 1 2 3 4 5 6 7 8 9 10 11 |
[root@byrd script]# date Mon Mar 31 21:40:22 CST 2014 [root@byrd script]# date -s 09:00:00 Mon Mar 31 09:00:00 CST 2014 [root@byrd script]# /bin/sh ntpdate.sh #测试脚本正常 31 Mar 21:40:52 ntpdate[1183]: step time server 64.4.10.33 offset 45636.346649 sec [root@byrd script]# date Mon Mar 31 21:40:58 CST 2014 [root@byrd script]# date -s 09:00:00 Mon Mar 31 09:00:00 CST 2014 [root@byrd script]# date #4分后,测试定时任务正常。 Mon Mar 31 21:44:28 CST 2014 |
将定时任务改回需要的效果
0 1 |
#This is a time synchronization BY:BYRD AT:2014-03-31 00 21 * * * /bin/sh /byrd/script/ntpdate.sh >/dev/null 2>&1 |
关于定时任务的说明:
0 1 2 3 4 5 6 7 |
# Example of job definition: # .---------------- minute (0 - 59) # | .------------- hour (0 - 23) # | | .---------- day of month (1 - 31) # | | | .------- month (1 - 12) OR jan,feb,mar,apr ... # | | | | .---- day of week (0 - 6) (Sunday=0 or 7) OR sun,mon,tue,wed,thu,fri,sat # | | | | | # * * * * * user-name command to be executed |
如果在使用ntpdate中有问题,可以参考:ntp同步SourceByrd's Weblog-https://note.t4x.org/system/linux-crontab-ntpdate/
申明:本文由BYRD原创(基于Centos6.4 X64),未经许可禁止转载!SourceByrd's Weblog-https://note.t4x.org/system/linux-crontab-ntpdate/ SourceByrd's Weblog-https://note.t4x.org/system/linux-crontab-ntpdate/
申明:除非注明Byrd's Blog内容均为原创,未经许可禁止转载!详情请阅读版权申明!