| # crontab -e SHELL=/bin/bash MAILTO=root@example.com PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin # 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 # backup using the rsbu program to the internal 4TB HDD and then 4TB external 01 01 * * * /usr/local/bin/rsbu -vbd1 ; /usr/local/bin/rsbu -vbd2 # Set the hardware clock to keep it in sync with the more accurate system clock 03 05 * * * /sbin/hwclock --systohc # Perform monthly updates on the first of the month # 25 04 1 * * /usr/bin/dnf -y update |
crontab 命令用于查看或编辑 cron 文件。
上面代码中的前三行设置了一个缺省环境。对于给定用户,环境变量必须是设置的,因为,cron 不提供任何方式的环境。SHELL 变量指定命令运行使用的 shell。这个示例中,指定为 Bash shell。MAILTO 变量设置发送 cron 作业结果的电子邮件地址。这些电子邮件提供了 cron 作业(备份、更新、等等)的状态,和你从命令行中手动运行程序时看到的结果是一样的。第三行为环境设置了 PATH 变量。但即使在这里设置了路径,我总是使用每个程序的完全限定路径。
在上面的示例中有几个注释行,它详细说明了定义一个 cron 作业所要求的语法。我将在下面分别讲解这些命令,然后,增加更多的 crontab 文件的高级特性。
| 01 01 * * * /usr/local/bin/rsbu -vbd1 ; /usr/local/bin/rsbu -vbd2 |
在我的 /etc/crontab 中的这一行运行一个脚本,用于为我的系统执行备份。
这一行运行我自己编写的 Bash shell 脚本 rsbu,它对我的系统做完全备份。这个作业每天的凌晨 1:01 (01 01) 运行。在这三、四、五位置上的星号(*),像文件通配符一样代表一个特定的时间,它们代表 “一个月中的每天”、“每个月” 和 “一周中的每天”,这一行会运行我的备份两次,一次备份内部专用的硬盘驱动器,另外一次运行是备份外部的 USB 驱动器,使用它这样我可以很保险。
接下来的行我设置了一个硬件时钟,它使用当前系统时钟作为源去设置硬件时钟。这一行设置为每天凌晨 5:03 分运行。
| 03 05 * * * /sbin/hwclock --systohc |
这一行使用系统时间作为源来设置硬件时钟。
我使用的第三个也是最后一个的 cron 作业是去执行一个 dnf 或 yum 更新,它在每个月的第一天的凌晨 04:25 运行,但是,我注释掉了它,以后不再运行。








