使用 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 <---- easiest
2. /usr/bin/vim.basic
...
Choose 1-2 [1]:
按 1
然后按 Enter
选择 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
确认更改,最后按 Enter
将更改写入文件。
退出后,你将在终端中看到一条确认消息:
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
命令,你将看到一个带有更新时间戳的新行,这表明该作业正在重复运行。