在 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 年之間,包括在內。
百分比(%
)
除非使用反斜槓()進行轉義,否則命令中的百分號(%)將更改為換行符,並且第一個%之後的所有資料將作為標準輸入傳送到命令。