Linux 中使用计划任务详解

linux5个月前发布 灯塔导航
104 0

在系统管理中,少不了 crontab 任务调度工具。使用 crontab,您可以在特定的日期和时间运行脚本和命令。要很好地使用它,您需要知道如何编辑 crontab 文件。

Understanding Crontab

crontab (cron table) 它是由 cron 守护进程使用的文件。cron 守护进程是 Linux 中的一个工具,它在预定时间运行系统上的任务。计划由 crontab 文件设置,该文件是一个简单的文本文件,包含命令列表和何时运行它们。crontab 文件中的每一行都有用于调度任务的特定格式。

Accessing the Crontab File

要打开用户指定的 crontab 文件,使用 crontab -e 命令。

Crontab File Syntax

理解 cron 语法是编辑 crontab 文件的关键。文件中的每一行都是一个 cron 作业,并遵循这种格式。

*     *     *   *    *        command to be executed
-     -     -   -    -
|     |     |   |    |
|     |     |   |    +----- day of the week (0 - 6) (Sunday=0)
|     |     |   +------- month (1 - 12)
|     |     +--------- day of the month (1 - 31)
|     +----------- hour (0 - 23)
+------------- min (0 - 59)

字段中的星号 (*) 表示每个值,如 每分钟、 每小时 、 每天

Editing the Crontab File

在 crontab 文件中,您可以使用上面的语法添加任务。例如,要在每天凌晨 3 点运行备份脚本。

0 3 * * * /path/to/yourscript.sh

保存并关闭该文件,cron 守护进程将使用新的任务调度启动。

Common Crontab Commands

下面是一些常见的 crontab 命令:

  • crontab -e 编辑 crontab 文件
  • crontab -l 显示 crontab 文件的内容
  • crontab -r 删除当前的 crontab
  • crontab -i 删除 crontab 之前带提示

Crontab Special Strings

Crontab 还支持特殊字符串来替换五个时间和日期字段

  • @reboot 在启动时运行一次
  • @yearly:每年运行一次,等同 “0 0 1 1 *”
  • @annually:等同 @yearly
  • @monthly:每月运行一次,等同 “0 0 1 “
  • @weekly:每周运行一次,等同 “0 0 0”
  • @daily:每天运行一次,等同 “0 0 *”
  • @hourly: 每小时运行一次,等同 “0 “

这些特殊的字符串使 crontab 文件更易于阅读和管理。

Handling Output

默认情况下,cron 发送带有每个作业输出的电子邮件。要更改输出的位置,请使用 shell 重定向。

30 2 * * * /path/to/yourscript.sh > /path/to/outputfile 2>&1

“>” 将脚本的输出发送到一个文件,而 “2>&1” 将错误输出发送到与标准输出相同的位置。

Final Thought

一定要测试 cron 任务,以确保它们按预期运行。

© 版权声明