Linux 安装crontab 及简单使用方法

crontab是什么

百度百科:crontab命令常见于Unix和类Unix的操作系统之中,用于设置周期性被执行的指令。该命令从标准输入设备读取指令,并将其存放于“crontab”文件中,以供之后读取和执行。通俗来讲就是执行定时任务的一个命令。

先检查你的服务器是否安装了crontab

rpm -qa | grep crontab
在这里插入图片描述
出现上图说明已经安装好了!!

如果没有安装好~~~~

分别执行:

yum -y install vixie-cron
yum -y install crontabs

简单说明:
vixie-cron 是 cron 的主程序;
crontabs 是用来安装、卸装、或列举用来驱动 cron 守护进程的表格的程序。

安装好了–启动和配置服务

手动方式:

service crond start     //启动服务
service crond stop      //关闭服务
service crond restart   //重启服务
service crond reload    //重新载入配置
service crond status    //查看crontab服务状态

同样可以设置开机自启动:

chkconfig --level 345 crond on
crontab文件格式:

*             *            *            *            *            command

分         时           日          月          周(几)         命令

特殊字符:

星号(*):代表’‘每’'的意思,例如month字段如果是星号,则表示每月都执行该命令。
逗号(,):表示分隔时段的意思,例如,“1,3,5,7,9”。
中杠(-):表示一个时间范围,例如“2-6”表示“2,3,4,5,6”。
正斜线(/):可以用正斜线指定时间的间隔频率,例如“0-23/2”表示每两小时执行一次。同时正斜线可以和星号一起使用,例如*/10,如果用在minute字段,表示每十分钟执行一次。

练习

准备:在/root/下新建一个shell文件–test.sh
[root@hwyuntrx ~]# vim test.sh
添加下面内容

nowtime=`date +"%Y-%m-%d %H:%M:%S"`
echo "hello cron "$nowtime

添加执行权限
[root@hwyuntrx ~]# chmod +x test.sh
运行:
[root@hwyuntrx ~]# ./test.sh
hello cron 2019-03-09 19:54:30

运行crontab –e 编写一条定时任务 */1 * * * * /root/test.sh 在每1分钟执行一次test.sh脚本。
添加如下命令

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

运行结果:
在这里插入图片描述

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

30 3,12 * * * /root/test.sh >> /root/test.log

每月每天每隔6小时的每30分钟执行test.sh脚本

30 */6 * * * /root/test.sh >> /root/test.log

每月每天早上8点到下午18点每隔2小时的每30分钟执行test.sh脚本

30 8-18/2 * * * /root/test.sh >> /root/test.log

每月每天晚上21点30分执行test.sh脚本

30 21 * * * /root/test.sh >> /root/test.log

每月1号、10号、22号凌晨4点45分执行test.sh脚本

45 4 1,10,22 * * /root/test.sh >> /root/test.log

8月份周一、周日凌晨1点10分执行test.sh脚本

10 1 * 8 6,0 /root/test.sh >> /root/test.log

每月每天每小时整点执行test.sh脚本

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

  • 7
    点赞
  • 27
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值