1、crontab
Crontab的服務進程名為crond,英文意為周期任務。顧名思義,crontab在Linux主要用于周期定時任務管理。通常安裝操作系統后,默認已啟動crond服務。crontab可理解為cron_table,表示cron的任務列表。類似crontab的工具還有at和anacrontab,但具體使用場景不同。
不同的系統,叫法可能不一樣,在Ubuntu下,服務名叫cron。
2、操作crontab
安裝(apt、yum等)好了以后
$ crontab -e
* * * * * date >> /tmp/date.txt
- Edit the crontab file for the current user:
crontab -e
- Edit the crontab file for a specific user:
sudo crontab -e -u {{user}}
- Replace the current crontab with the contents of the given file:
crontab {{path/to/file}}
- View a list of existing cron jobs for current user:
crontab -l
- Remove all cron jobs for the current user:
crontab -r
- Sample job which runs at 10:00 every day (* means any value):
0 10 * * * {{command_to_execute}}
- Sample job which runs every minute on the 3rd of April:
* * 3 Apr * {{command_to_execute}}
- Sample job which runs a certain script at 02:30 every Friday:
30 2 * * Fri {{/absolute/path/to/script.sh}}
3、重點說明
# 計劃任務定義的例子:
# .---------------- 分 (0 - 59)
# | .------------- 時 (0 - 23)
# | | .---------- 日 (1 - 31)
# | | | .------- 月 (1 - 12)
# | | | | .---- 星期 (0 - 7) (星期日可為0或7)
# | | | | |
# * * * * * 執行的命令
* * * * * date >> /time.txt 2>&1
定時任務的結構如上,前面是定義定時,后面是命令。
命令寫法,差之毫厘,謬之千里:
# 每天3點執行
0 3 * * * command
# 三點的每分鐘都執行
* 3 * * * command
內容需要重定向輸出到指定文件,否則容易造成無法獲取執行日志的問題。形如:
ls >> /tmp/ls.txt 2>&1