linux定时任务,时间纠正和同步
编辑/etc/crontab增加定时任务
vi /etc/crontab
SHELL=/bin/bashPATH=/sbin:/bin:/usr/sbin:/usr/binMAILTO=root# For details see man 4 crontabs# 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*/1 * * * * root syncdate
详解
PATH=/sbin:/bin:/usr/sbin:/usr/bin
表示环境变量,跟/etc/profile的环境变量差不多。
*/1 * * * * root syncdate
表示每分钟使用root用户执行syncdate命令
*/1 * * * *
表示每分钟执行一次
增加同步服务器时间syncdate命令
编辑脚本
vi /usr/sbin/syncdate
脚本内容
echo "|-正在尝试从0.同步时间..";ntpdate -u 0.if [ $? = 1 ];thenecho "|-正在尝试从1.同步时间..";ntpdate -u 1.fiif [ $? = 1 ];thenecho "|-正在尝试从0.asia.同步时间..";ntpdate -u 0.asia.fiif [ $? = 1 ];thenecho "|-正在尝试从同步时间..";getBtTime=$(curl -sS --connect-timeout 3 -m 60 /api/index/get_time)if [ "${getBtTime}" ];thendate -s "$(date -d @$getBtTime +"%Y-%m-%d %H:%M:%S")"fifiecho "|-正在尝试将当前系统时间写入硬件..";hwclock -wdateecho "|-时间同步完成!";~
脚本赋予可执行权限
chmod +x /usr/sbin/syncdate
配置示例
实例1:每1分钟执行一次command
命令:* * * * * command
实例2:每小时的第3和第15分钟执行
命令:3,15 * * * * command
实例3:在上午8点到11点的第3和第15分钟执行
命令:3,15 8-11 * * * command
实例4:每隔两天的上午8点到11点的第3和第15分钟执行
命令:3,15 8-11 */2 * * command
实例5:每个星期一的上午8点到11点的第3和第15分钟执行
命令:3,15 8-11 * * 1 command
实例6:每晚的21:30重启smb
命令:30 21 * * * /etc/init.d/smb restart
实例7:每月1、10、22日的4 : 45重启smb
命令:45 4 1,10,22 * * /etc/init.d/smb restart
实例8:每周六、周日的1 : 10重启smb
命令:10 1 * * 6,0 /etc/init.d/smb restart
实例9:每天18 : 00至23 : 00之间每隔30分钟重启smb
命令:0,30 18-23 * * * /etc/init.d/smb restart
实例10:每星期六的晚上11 : 00 pm重启smb
命令:0 23 * * 6 /etc/init.d/smb restart
实例11:每一小时重启smb
命令:* */1 * * * /etc/init.d/smb restart
实例12:晚上11点到早上7点之间,每隔一小时重启smb
命令:* 23-7/1 * * * /etc/init.d/smb restart
实例13:每月的4号与每周一到周三的11点重启smb
命令:0 11 4 * mon-wed /etc/init.d/smb restart
实例14:一月一号的4点重启smb
命令:0 4 1 jan * /etc/init.d/smb restart
实例15:每小时执行/etc/cron.hourly目录内的脚本
命令:01 * * * * root run-parts /etc/cron.hourly
说明:
run-parts这个参数了,如果去掉这个参数的话,后面就可以写要运行的某个脚本名,而不是目录名了
如果觉得《Linux使用crond定时任务详解 定期同步服务器时间。》对你有帮助,请点赞、收藏,并留下你的观点哦!