cron是定时任务执行程序
cron有多处配置,/etc/crontab和/var/spool/cron,前者是全局配置,后者是用户配置,使用crontab -e命令配置的是用户配置,用户配置只能用命令,而/etc/crontab的配置可以直接用vim修改。
配置会被cron每分钟读取一下,所以修改完后保存,就会被执行了,如果觉得不稳妥,可以systemctl restart crond重启crond

配置如下所示,没有太多东西:

[root@ ~]# crontab -l
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
  */10  *  *  *  * root       /usr/sbin/logrotate -s /var/lib/logrotate/logrotate.status /etc/logrotate.d/nginx_log >/dev/null 2>&1

/etc/cron.d也是定时任务脚本存放的地方,里面有0hourly、dailyjobs、timezone.cron定时任务,我们如果自己写定时任务,也可以放到这里。
0hourly脚本中表示放在/etc/cron.hourly中的脚本会每小时执行一次,如果我们有每小时要执行的任务,也可以放在/etc/cron.hourly中。
在etc下还有/etc/cron.{daily,weekly,monthly}三个目录,它们的脚本是被anacron执行的,而anacron的执行方式则是放在/etc/cron.hourly/0anacron里面,每个小时执行一次

anacron是一个按周期执行的程序,和cron有一些不同,只能以天为单位执行定时任务
原理是比较现在时间和历史执行时间来判断是否需要执行,所以当预设执行时间服务器关机了,那么开机后任务会执行掉
/etc/anacrontab是anacron的配置文件,默认有一天、一周、一月这三种周期,只要在这里配置好,系统就会自动执行定时任务了

[root@ cron.d]# cat /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.daily工作来说明一下/etc/anacrontab的执行过程:
1.读取 /var/spool/anacron/cron.daily 文件中 anacron 上一次执行的时间。
2.和当前时间比较,如果两个时间的差值超过1天,就执行 cron.daily 工作。
3.只能在 03:00-22:00 执行这个工作。
4.执行工作时强制延迟时间为5分钟,再随机延迟0~45分钟。
5.使用nice命令指定默认优先级,使用 run-parts 脚本执行 /etc/cron.daily 目录中所有的可执行文件。

/etc/cron.{daily,weekly,monthly} 目录中的定时任务会被anacron调用
/etc/cron.daily目录下有logrotate脚本,其中执行了log的定时任务,所以logrotate的定时任务默认一天执行一次,logrotate.d下的脚本是被anacron执行的,如果在crontable也配置了脚本的定时执行,实际上会重复执行