簡(jiǎn)介
Linux crontab和Windows task schedules非常的相似。Crontab可以用來(lái)在系統(tǒng)中定期的執(zhí)行任務(wù)。比如:寫了一個(gè)爬蟲需要每天早上八點(diǎn)執(zhí)行,就可以用到Crontab;安裝的Tomcat服務(wù)器需要每天凌晨重啟一次,也可以使用到Crontab??傊?,幾乎所有的定時(shí)任務(wù),我們都可以通過(guò)Crontab這個(gè)工具來(lái)完成。
安裝
yum install cronie`
Crontab在Linux上的結(jié)構(gòu)
[圖片上傳失敗...(image-1306c5-1537338963372)]
從左到右依次為:
[分鐘] [小時(shí)] [每月的某一天] [每年的某一月] [每周的某一天] [執(zhí)行的命令]
注意:請(qǐng)留意每個(gè)選項(xiàng)的取值范圍。
如何 添加/編輯 Crontab
- 添加或更新crontab中的命令
crontab -e
默認(rèn)情況下,系統(tǒng)會(huì)編輯當(dāng)前登錄用戶的crontab命令集合。需要編輯其他用戶的命令集合,需要使用到如下的命令
crontab -u username -e
查看Crontab命令集合
- 查看當(dāng)前系統(tǒng)登錄用戶的Crontab命令集合
crontab -l
- 查看其他用戶的Crontab命令集合
crontab -u username -l
20個(gè)超實(shí)用的Crontab使用實(shí)例
- 每天 02:00 執(zhí)行任務(wù)
0 2 * * * /bin/sh backup.sh
- 每天 5:00和17:00執(zhí)行任務(wù)
0 5,17 * * * /scripts/script.sh
- 每分鐘執(zhí)行一次任務(wù)
通常情況下,我們并沒(méi)有每分鐘都需要執(zhí)行的腳本(默默的想到了12306--)
* * * * * /scripts/script.sh
- 每周日 17:00 執(zhí)行任務(wù)
0 17 * * sun /scripts/script.sh
- 每 10min 執(zhí)行一次任務(wù)
*/10 * * * * /scripts/monitor.sh
- 在特定的某幾個(gè)月執(zhí)行任務(wù)
* * * jan,may,aug * /script/script.sh
- 在特定的某幾天執(zhí)行任務(wù)
0 17 * * sun,fri /script/scripy.sh
在每周五、周日的17點(diǎn)執(zhí)行任務(wù)
- 在某個(gè)月的第一個(gè)周日?qǐng)?zhí)行任務(wù)
0 2 * * sun [ $(date +%d) -le 07 ] && /script/script.sh
- 每四個(gè)小時(shí)執(zhí)行一個(gè)任務(wù)
0 */4 * * * /scripts/script.sh
- 每周一、周日?qǐng)?zhí)行任務(wù)
0 4,17 * * sun,mon /scripts/script.sh
- 每個(gè)30秒執(zhí)行一次任務(wù)
我們沒(méi)有辦法直接通過(guò)上訴類似的例子去執(zhí)行,因?yàn)樽钚〉氖?min。但是我們可以通過(guò)如下的方法。
* * * * * /scripts/script.sh
* * * * * sleep 30; /scripts/script.sh
- 多個(gè)任務(wù)在一條命令中配置
* * * * * /scripts/script.sh; /scripts/scrit2.sh
- 每年執(zhí)行一次任務(wù)
@yearly /scripts/script.sh
@yearly 類似于“0 0 1 1 *”。它會(huì)在每年的第一分鐘內(nèi)執(zhí)行,通常我們可以用這個(gè)發(fā)送新年的問(wèn)候。
- 每月執(zhí)行一次任務(wù)
@yearly /scripts/script.sh
- 每周執(zhí)行一次任務(wù)
@yearly /scripts/script.sh
- 每天執(zhí)行一次任務(wù)
@yearly /scripts/script.sh
- 每分鐘執(zhí)行一次任務(wù)
@yearly /scripts/script.sh
- 系統(tǒng)重啟時(shí)執(zhí)行
@reboot /scripts/script.sh
- 將 Cron 結(jié)果重定向的特定的賬戶
默認(rèn)情況下,cron 只會(huì)將結(jié)果詳情發(fā)送給 cron 被制定的用戶。如果需要發(fā)送給其他用戶,可以通過(guò)如下的方式:
# crontab -l
MAIL=bob
0 2 * * * /script/backup.sh
- 將所有的 cron 命令備份到文本文件當(dāng)中
這是一個(gè)當(dāng)我們丟失了cron命令后方便快速的一個(gè)恢復(fù)方式。
下面是利用這個(gè)方式恢復(fù)cron的一個(gè)小例子。(看看就行~)
首先:檢查當(dāng)前的cron
# crontab -l
MAIL=rahul
0 2 * * * /script/backup.sh
然后:備份cron到文件中
# crontab -l > cron-backup.txt
# cat cron-backup.txt
MAIL=rahul
0 2 * * * /script/backup.sh
接著:移除當(dāng)前的cron
# crontab -r
# crontab -l
no crontab for root
恢復(fù):從text file中恢復(fù)
# crontab cron-backup.txt
# crontab -l
MAIL=rahul
0 2 * * * /script/backup.sh