安装
一般情况下crond、crontab是安装好的,这里主要提一下万一没有crontab你别想着直接用yum去安装crond或者crontab因为你会发现找不到包,其实定时任务的包是cronie。
[root@localhost log]# yum install -y cronie
关于 crond 和 crondtab 常用命令
- crond常用命令
# 启动服务
[root@localhost log]# systemctl start crond
# 停止服务
[root@localhost log]# systemctl stop crond
# 重启服务
[root@localhost log]# systemctl restart crond
# 重载配置文件
[root@localhost log]# systemctl reload crond
# 查看状态
[root@localhost log]# systemctl status crond
- crontab常用命令
# 设定某个用户的cron服务
crontab -u
# 显示crontab文件(显示已设置的定时任务)
crontab -l
# 编辑crontab文件(编辑定时任务)
crontab -e
# 删除crontab文件(删除定时任务)
crontab -r
# 删除crontab文件提醒用户(删除定时任务)
crontab -i
配置
- 直接修改配置文件
将定时任务添加到 /etc/crontab 的最后一行
SHELL=/bin/bash
PATH=/sbin:/bin:/usr/sbin:/usr/bin
MAILTO=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
# 此处就是配置的定时任务
0,30 * * * * root /opt/databak/backup.sh
其中的时间格式可以为
* :表示任意的时刻;如小时位 * 则表示每个小时
n :表示特定的时刻;如小时位 5 就表示5时
n,m :表示特定的几个时刻;如小时位 1,10 就表示1时和10时
n-m :表示一个时间段;如小时位 1-5 就表示1到5点
*/n : 表示每隔多少个时间单位执行一次;如小时位 */1 就表示每隔1个小时执行一次命令,也可以写成 1-23/1
- 使用crontab -e 命令编辑
[root@localhost log]# crontab -e 0,30 * * * * root /opt/databak/backup.sh
- 重载配置
[root@localhost log]# systemctl reload crond
遇到的问题
-
手动删除日志文件后,无法在输出日志
解决办法:
# 日志文件 cron 的位置在 /etc/log/
# 重启日志服务
[root@localhost log]# systemctl restart rsyslog
- 在 crontab 中添加定时任务时,使用了生成工具生成的 cron 表达式。但是,这样并不行,这种格式是不被允许的,还是需要根据 crontab 文件中的说明进行配置。