在 ubuntu(或大多数其他 Linux 操作系统)上创建一个新的 cron

你只需键入即可创建新的 cron 条目

crontab -e

在命令行上。如果这是你第一次编辑 crontab(文件),系统将提示你选择编辑器:

no crontab for <user> - using an empty one

Select an editor.  To change later, run 'select-editor'.
  1. /bin/ed
  2. /bin/nano        <---- easiest
  3. /usr/bin/vim.basic
  4. /usr/bin/vim.tiny

Choose 1-4 [2]: 

只需按照提示选择你的编辑器,你的 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 manual pages of crontab(5) and cron(8)
#
# m h  dom mon dow   command

如你所见,文本中已有一个示例条目:

0 5 * * 1 tar -zcf /var/backups/home.tgz /home/

这将在/var/backups/中创建一个名为 home.tgz 的备份文件。这个 crontab 的时机将是

every monday (first day of week) at 5:00 A.M.

如果你已将该行输入为 crontab,那么你现在要做的就是保存 crontab 文件。例如使用 nano 编辑器,这是通过 <Ctrl> + <X> 完成的 - 然后确认用 Y 保存。

要检查你的 crontab,只需输入

crontab -l 

在控制台中。

你可以选择更多关于 crontimings 的信息:

 # * * * * *  command to execute
 # │ │ │ │ │
 # │ │ │ │ │
 # │ │ │ │ └───── day of week (0 - 6) (0 to 6 are Sunday to Saturday, or use names; 7 is Sunday, the same as 0)
 # │ │ │ └────────── month (1 - 12)
 # │ │ └─────────────── day of month (1 - 31)
 # │ └──────────────────── hour (0 - 23)
 # └───────────────────────── min (0 - 59)

cronjobs 中的特殊字符是:

星号(*

星号表示 cron 表达式匹配字段的所有值。例如,在第 4 个字段(月)中使用星号表示每个月。

斜线(/

斜杠描述范围的增量。例如,第 1 场(分钟)中的 3-59 / 15 表示小时的第 3 分钟,之后每 15 分钟。形式“* / …”等同于“first-last / …”形式,即在该字段的最大可能范围内的增量。

逗号(,

逗号用于分隔列表的项目。例如,在第 5 个字段(星期几)中使用“MON,WED,FRI”表示星期一,星期三和星期五。

连字符(-

连字符定义范围。例如,2000 - 2010 年表明每年在 2000 年至 2010 年之间,包括在内。

百分比(%

除非使用反斜杠()进行转义,否则命令中的百分号(%)将更改为换行符,并且第一个%之后的所有数据将作为标准输入发送到命令。