Linux下Crontab定时执行命令

Linux下Crontab定时执行命令


目录

  1. Crontab概述及安装
  2. Crontab规则
  3. 常见例子

1. Crontab概述及安装

1. Crontab指令是Linux下执行定时任务的一个命令。
2. 检查服务器是否安装了crontab
rpm -qa | grep crontab

在这里插入图片描述

3. 如果没有安装好,执行安装命令
  1. vixie-cron 是 cron 的主程序;
  2. crontabs 是用来安装、卸装、或列举用来驱动 cron 守护进程的表格的程序。
yum -y install vixie-cron
yum -y install crontabs
4. 安装好久可以启动和配置服务
service crond start     //启动服务
service crond stop      //关闭服务
service crond restart   //重启服务
service crond reload    //重新载入配置
service crond status    //查看crontab服务状态
5. 设置开机自启动
chkconfig --level 345 crond on

2. Crontab规则

1. crontab文件格式
	*	 	*	 	*	 	*	 	* 			command
    分	    时      日      月       周(几)       命令
2. 特殊字符解释
  1. * :代表“每”的意思,例如month字段如果是 * 号,则表示每个月执行该命令
  2. , : 表示分隔时段的意思,例如,“1,3,5,7,9”
  3. - : 表示一个时间范围,例如“2-6”表示“2,3,4,5,6”。
  4. / : 表示时间的间隔频率,例如“0-23/2”表示每两小时执行一次。同时 / 可以和 * 一起使用,例如 * /10 ,如果用在minute字段,表示每10分钟执行一次。
3. 练习
  1. 在目录下新建一个shell文件:test.sh,写入

    #!/bin/bash
    
    echo "hello world!"
    
  2. 给test.sh可执行权限

    chmod 755 test.sh
    
  3. 执行contab -e编写定时任务,每分钟执行一次test.sh脚本。

    */1 * * * * /a8root/home/lijinwang/test/test.sh >> /a8root/home/lijinwang/test/test.log
    
  4. 结果。
    在这里插入图片描述


3. 常见例子

  1. 每月每天凌晨3点30分和中午12点20分执行test.sh脚本

    30 3,12 * * * /root/test.sh >> /root/test.log
    
  2. 每月每天每隔6小时的每30分钟执行test.sh脚本

    30 */6 * * * /root/test.sh >> /root/test.log
    
  3. 每月每天早上8点到下午18点每隔2小时的每30分钟执行test.sh脚本

    30 8-18/2 * * * /root/test.sh >> /root/test.log
    
  4. 每月每天晚上21点30分执行test.sh脚本

    30 21 * * * /root/test.sh >> /root/test.log
    
  5. 每月1号、10号、22号凌晨4点45分执行test.sh脚本

    45 4 1,10,22 * * /root/test.sh >> /root/test.log
    
  6. 8月份周一、周日凌晨1点10分执行test.sh脚本

    10 1 * 8 6,0 /root/test.sh >> /root/test.log
    
  7. 每月每天每小时整点执行test.sh脚本

    00 */1 * * * /root/test.sh >> /root/test.log
    

猜你喜欢

转载自blog.csdn.net/weixin_41910694/article/details/108134125