选项-r表示删除定时任务
[root@centos7 ~]# crontab -r [root@centos7 ~]# crontab -l no crontab for root
使用crontab时经常会遇到的一个问题是,在命令行下能够正常执行的命令或脚本,设置了定时任务时却不能正常执行。造成这种情况的原因一般是因为crond为命令或脚本设置了与登录shell不同的环境变量
[root@centos7 ~]# head -3 /etc/crontab SHELL=/bin/bash PATH=/sbin:/bin:/usr/sbin:/usr/bin MAILTO=root [root@centos7 ~]# [root@centos7 ~]# echo $PATH /usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/root/bin [root@centos7 ~]#
这里crond的PATH和shell中的值不同,PATH环境变量定义了shell执行命令时搜索命令的路径。关于环境变量更多的内容,将在shell编程的文章里详细说明。
对于系统级别的定时任务,这些任务更加重要,大部分linux系统在/etc中包含了一系列与 cron有关的子目录:/etc/cron.{hourly,daily,weekly,monthly},目录中的文件定义了每小时、每天、每周、每月需要运行的脚本,运行这些任务的精确时间在文件/etc/crontab中指定。如:
SHELL=/bin/bash PATH=/sbin:/bin:/usr/sbin:/usr/bin MAILTO=root HOME=/ # run-parts 01 * * * * root run-parts /etc/cron.hourly 02 4 * * * root run-parts /etc/cron.daily 22 4 * * 0 root run-parts /etc/cron.weekly 42 4 1 * * root run-parts /etc/cron.monthly
对于24小时开机的服务器来说,这些任务的定期运行,保证了服务器的稳定性。但注意到这些任务的执行一般都在凌晨,对于经常需要关机的linux计算机(如笔记本)来说,很可能在需要运行cron的时候处于关机状态,cron得不到运行,时间长了会导致系统变慢。对于这样的系统,linux引入了另一个工具anacron来负责执行系统定时任务。
anacron的目的并不是完全替代cron,是作为cron的一个补充。anacron的任务定义在文件/etc/anacrontab中:
# /etc/anacrontab: configuration file for anacron # See anacron(8) and anacrontab(5) for details. SHELL=/bin/sh PATH=/sbin:/bin:/usr/sbin:/usr/bin MAILTO=root # the maximal random delay added to the base delay of the jobs RANDOM_DELAY=45 # the jobs will be started during the following hours only START_HOURS_RANGE=3-22 #period in days delay in minutes job-identifier command 1 5 cron.daily nice run-parts /etc/cron.daily 7 25 cron.weekly nice run-parts /etc/cron.weekly @monthly 45 cron.monthly nice run-parts /etc/cron.monthly
与cron是作为守护进程运行的不同,anacron是作为普通进程运行并终止的。对于定义的每个任务,anacron在系统启动后将会检查应当运行的任务,判断上一次运行到现在的时间是否超过了预定天数(/etc/anacrontab中任务行第一列),如果大于预定天数,则会延迟一个时间(/etc/anacrontab中任务行第二列)之后运行该任务。这样就保证了任务的执行。关于anacron的更多内容,请查阅相关文档。










