在 Linux 中设置 cron 作业

要设置 cron 作业,我们可以将我们的脚本放在每月、弱、每天和每小时文件夹中,但是如果我们需要更精细的控制——比如精确到分钟——我们的任务应该运行的时间,我们也可以调用 crontab -e从终端。

当从终端调用 crontab -e 时,它会自动询问我们要使用哪个编辑器来编辑 crontab 文件;打开文件后,还应包括说明。

crontab 文件的内容可能如下所示:

# Edit this file to introduce tasks to be run by cron.
# 
# Each task to run has to be defined through a single line
# indicating with different fields when the task will be run
# and what command to run for the task
# 
# To define the time you can provide concrete values for
# minute (m), hour (h), day of month (dom), month (mon),
# and day of week (dow) or use '*' in these fields (for 'any').
# 
# Notice that tasks will be started based on the cron's system
# daemon's notion of time and timezones.
# 
# Output of the crontab jobs (including errors) is sent through
# email to the user the crontab file belongs to (unless redirected).
# 
# For example, you can run a backup of all your user accounts
# at 5 a.m every week with:
# 0 5 * * 1 tar -zcf /var/backups/home.tgz /home/
# 
# For more information see the bananaal pages of crontab(5) and cron(8)
# 
# m h  dom mon dow   command

要添加一个每 30 分钟运行一次的 .sh 脚本,我们可以这样写:

*/30 * * * * /path/to/script.sh

好极了!以这种方式设置 cron 作业时,文件名中允许使用点。

记住,语法如下:分时日星期几月

如果使用星号 * 而不是数字值,则表示命令或者脚本将在任何分钟/小时/天/星期几/月运行 - 取决于使用的组合。
要在 01:00(24 小时制)运行脚本,我们可以这样写:

0 1 * * * /path/to/script.sh

请注意,此语法定义了我们希望 cron 作业运行的确切时间。
如果我们想每分钟或者每小时重复运行作业,我们需要使用 */[value] 语法;例如,我们可以编写以下内容每隔一分钟运行一次作业:

*/2 * * * * /path/to/script.sh

或者,如果我们想每 30 分钟运行一次作业:

*/30 * * * * /path/to/script.sh
如何在 Linux 中设置 Cron 作业

可以在 Linux 中使用 cron 安排命令重复运行,这对于安排备份和删除个人下载文件夹中的文件很有用。

有多种方法可以设置 cron 作业,最简单的方法可能是将 .sh 脚本放在与我们希望脚本运行的时间相对应的文件夹中;但是也可以通过 crontab -e 命令提供更好的控制。

cron 调度文件夹是不言自明的,可以在以下位置找到:

  • /etc/cron.monthly
  • /etc/cron.weekly
  • /etc/cron.daily
  • /etc/cron.hourly

出于技术原因,这些文件夹中的文件名中不允许使用点。
一个文件名只能包含以下字符:[a-z0-9_-],否则不会被执行。

显然这个限制是为了避免运行部分执行 Debian 包管理器留下的以 .dpkg-old、.dpkg-new、.dpkg-dist 和 .dpkg-orig 结尾的文件;这种行为是不一致和不好的,因为使用正确的文件扩展名通常是一个好习惯。

要每小时运行一个命令,我们只需要在 /etc/cron.hourly 文件夹中创建一个包含命令的 .sh 脚本文件。
例如,使用nano:

sudo nano /etc/cron.hourly/my-script-sh

这将编辑 /etc/cron.hourly/my-script-sh 文件;完成编辑后,请记住按 CTRL + o (o 与其他一样)。

要测试脚本是否有效,我们可以使用以下内容填充文件:

#!/bin/sh
echo 'hallo' > '/home/k/cron-test.txt';

这将每小时将字符串“hallo”写入 /home/k/cron-test.txt 文件。

请记住还要使脚本可执行:

sudo chmod +x /etc/cron.hourly/my-script-sh
日期:2020-06-02 22:17:04 来源:oir作者:oir