使用 crontab -e 创建周期性作业
在这一步中,你将学习如何使用 cron 调度周期性任务。与只运行一次作业的 at 不同,cron 旨在按计划重复运行作业。你将在一个名为 crontab 的特殊文件中管理你的调度作业。
要编辑用户的 crontab 文件,可以使用 crontab -e 命令。其中 -e 代表「编辑」(edit)。
让我们打开 crontab 文件进行编辑。
crontab -e
如果这是你第一次运行 crontab -e,系统可能会提示你选择默认的文本编辑器。我们建议选择 nano,因为它非常易于使用。
Select an editor. To change later, run 'select-editor'.
1. /bin/nano <---- 最简单
2. /usr/bin/vim.basic
...
Choose 1-2 [1]:
输入 1 然后按回车键选择 nano。crontab 文件将打开。除了几行解释如何使用它的注释外,文件内容基本是空的。
crontab 条目具有特定的格式,包含六个字段:
分钟 小时 日 月 星期 命令
时间字段中的星号(*)充当通配符,表示「每」。对于我们的任务,我们希望每分钟运行一次命令。这非常适合测试,因为我们不需要等待太久就能看到结果。「每分钟」的调度配置是 * * * * *。
现在,在文件末尾添加一行新内容,调度一个将当前日期和时间追加到项目目录中名为 cron_log.txt 的日志文件的作业。
* * * * * date >> ~/project/cron_log.txt
添加该行后,你的编辑器内容应该如下所示:
## 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 manual pages of crontab(5) and cron(8)
#
## m h dom mon dow command
* * * * * date >> ~/project/cron_log.txt
要保存文件并退出 nano,请按 Ctrl-X,然后按 Y 确认更改,最后按回车键写入文件。
退出后,你会在终端看到一条确认消息:
crontab: installing new crontab
这意味着你的新 cron 作业已激活。cron 守护进程现在将每分钟检查一次此文件并执行你的命令。
等待至少一分钟。然后,验证日志文件是否已创建。
ls -l ~/project/cron_log.txt
你应该能看到列出的文件。
-rw-r--r-- 1 labex labex 29 Jan 1 12:15 /home/labex/project/cron_log.txt
现在,查看其内容。
cat ~/project/cron_log.txt
输出将显示命令第一次执行时的日期和时间。
Mon Jan 1 12:15:01 UTC 2024
如果你再等一分钟并再次运行 cat 命令,你会看到带有更新时间戳的新行,这证明作业正在重复运行。