用户访问控制

要允许用户访问 crontab,可以分别使用 /etc/cron.allow 和 /etc/cron.deny 文件来允许或者拒绝访问。
简单地将一个用户名放在 2 个文件中的任何一个中,以允许或者拒绝对 crontab 的访问。

如果 /etc/cron.allow 文件存在,则不会使用 /etc/cron.deny 文件。

在默认安装中,只有一个空文件 /etc/cron.deny 将存在。

如果这两个文件都不存在,则只有 root 用户才能通过 cron 安排作业。

如何编辑 crontab

编辑 crontab 的最佳方法是使用命令 crontab -e 。
另一种方法是:

1. su to the user whose cron you want to change
2. crontab -l > file      [ copy the crontab to a file ].
3. vi file                [ make changes to the file as per your need ]
4. crontab file           [ this makes the "file" as new crontab ]

此后无需重新启动 cron 守护程序。

crontab 语法

设置用户级 crontab 有点不同。
/var/spool/cron 中的文件不是直接编辑的。
相反,使用名为 crontab 的程序来操作它们。
crontab 命令的语法是:

Usage:
 crontab [options] file
 crontab [options]
 crontab -n [hostname]
Options:
 -u [user]  define user
 -e         edit user's crontab
 -l         list user's crontab
 -r         delete user's crontab
 -i         prompt before deleting
 -n [host]  set host in cluster to run users' crontabs
 -c         get host in cluster to run users' crontabs
 -s         selinux context
 -x [mask]  enable debugging
CentOS/RHEL:cron 教程

Cron 是一个基于时间的作业调度程序,它被配置为在给定的时间或者间隔运行命令。
每个用户都有一个 cron 表,它定义了要执行的内容和间隔。
crontab 命令用于创建、修改和查看 cron 作业。

设置 cron 作业的示例

下面是一些使用 crontab 来理解如何安排任务的例子:
示例:每天午夜后五分钟运行作业:

5 0 *  *  *     /home/oracle/scan_asm_devices.sh

示例:在每个月的 1 号下午 5:30 运行作业:

30 17 1  *  *   mail -s "It's 5:30pm"

示例:每周一 4:05 运行作业。

5  4  *  *  mon     echo "run at 5 after 4 every monday"

配置文件和目录

Cron 由一组称为 crontabs 的文件控制。

在 /etc/crontab 中有主文件,在 /var/spool/cron/ 中有用户的 crontab 文件。
在后一个目录中,文件的名称与用户的用户名相同。

/etc/crontab 文件会定期自动执行多个子目录中的项目。
放置在不同目录 /etc/cron.* 中的脚本按照下面给出的时间间隔运行。
这些目录中的所有脚本都以 root 权限运行。

目录时间
/etc/cron.hourly每小时的第一分钟
/etc/cron.daily每天凌晨 3:05 至晚上 10.55
/etc/cron.weekly自上次执行后 7 天后的凌晨 3:25 至晚上 11:10 之间
/etc/cron.monthly自上次执行后一个月后的凌晨 3:45 至晚上 11:30 之间

系统管理员需要做的就是其中一个目录中放置一个 shell 脚本或者一个可执行文件的链接,它会在适当的时间自动运行。

之路 on it Road.com

解释时间和日期字段

每个cron命令有5个时间和日期字段,后面跟着一个用户名[可选],如果这是系统crontab文件,后面会跟着一个命令。
当时间/日期字段指定的时间与当前时间匹配时,将执行命令。

field          allowed values
-----          --------------                  
minute         0-59                  
hour           0-23                  
day of month   0-31                  
month          0-12 (or names, see below)                  
day of week    0-7 (0 or 7 is Sun, or use names)

一个字段可能是一个星号 (*),它总是代表 first to last 。
所以当在月份字段中使用时,它表示从0(Jan)到12(Dec)的每个月。

Cron 作业示例:

# 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
 |  |  |  |  |
 0  1  *  *  *  [user-name] [command to be executed]
日期:2020-09-17 00:12:08 来源:oir作者:oir