crontab命令
执行命令
增加一条crontab
crontab -e
内容
# 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
# | | | | |
# * * * * * command to be executed
0 0 1 * * echo `date`
每个月1号0点0分 执行一条
echo `data`
root用户为其他用户指定定时任务
crontab -u user -e
其他参数
-l 列出一个用户的定时任务
-r (delete user's crontab)
-i (prompt before deleting user's crontab)
-s (selinux context)
内容保存在/var/spool/
目录下
root@localhost cron]# crontab -u user2 -e
no crontab for user2 - using an empty one
crontab: installing new crontab
[root@localhost cron]# ls
user1 user2
[root@localhost cron]# cat user2
0 0 1 * * echo `data`
[root@localhost cron]#
crontab文件
[root@localhost etc]# cat 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
*/1 * * * * root echo `data`
crontab文件和crontab -e命令区别
格式不同
前者比后者多了一个用户,而这样子也有了好处,那就是root用户可以统一管理每个用户的cron
使用范围
修改/etc/crontab这种方法只有root用户能用,这种方法更加方便与直接直接给其他用户设置计划任务,而且还可以指定执行shell等等,
crontab -e这种所有用户都可以使用,普通用户也只能为自己设置计划任务。然后自动写入/var/spool/cron/usename。
crontab -e 是针对用户的cron来设计的,如果是系统的例行性任务,该怎么办?是否还是需要以crontab -e来管理例行性命令?当然不需要,您只需要编辑/etc/crontab文件就可以了。需要注意的是:crontab -e的作用其实是/usr/bin/crontab这个执行文件,但是/etc/crontab是个纯文本文件,可以root的身份编辑这个文件。
语法检查
- crontab 会进行语法检查
- vi 不会
重启服务
基本上,cron服务的最低检测时间单位是分钟,所以cron会每分钟读取一次/etc/crontab与/var/spool/cron中的数据内容,因此,只要您编辑完/etc/crontab文件并且保存之后,crontab时设定就会自动执行。
注意:在linux下的crontab会自动帮我们每分钟重新读取一次/etc/crontab的例行工作事项,但是某些原因或在其他的unix系统中,由于crontab是读到内存中,所以在您修改完/etc/crontab之后可能并不会马上执行,这时请重新启动crond服务。
日志文件
开启日志文件
ubuntu系统需要开启日志文件
在 Ubuntu服务器上 查看定时任务的日志时,并没有在 /var/log/cron.log 文件。
看配置发现是默认没有开启 crontab 日志记录。
修改配置文件
sudo vim /etc/rsyslog.d/50-default.conf
取消 cron
行的注释
重启 系统日志服务 即可
sudo service rsyslog restart
查看日志文件
CentOS: tail -f /var/log/cron
Ubuntu: tail -f /var/log/cron.log
这个日志文件中存储了crontab的日志信息
如何防止二次运行
如何防止二次运行
查看/etc/cron
[root@localhost ~]# cat /etc/cron.d/0hourly
# Run the hourly jobs
SHELL=/bin/bash
PATH=/sbin:/bin:/usr/sbin:/usr/bin
MAILTO=root
01 * * * * root run-parts /etc/cron.hourly
run-parts 脚本作用就是执行每一条cron指令,并且给每一个任务增加一个flag。从而防止一个记录执行多遍。