Linux 上可以利用cron,實(shí)現(xiàn)任務(wù)的調(diào)度,比如每晚八點(diǎn)半執(zhí)行一個(gè)php腳本。
或者是調(diào)用shell腳本等
只需要編輯cron配置就行了
打開(kāi)終端輸入:
crontab -e
此時(shí)會(huì)提示:
no crontab for root - 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]: 2
crontab: installing new crontab
選擇2 使用nano編輯,如果你習(xí)慣vi可以選3,4.
之后就可以編輯cron配置文件了:
# 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
30 20 * * * php /path/your.php
配置的含義:
第一個(gè)參數(shù) 分鐘?。?-59)
第二個(gè)參數(shù) 小時(shí)?。?-23)
第三個(gè)參數(shù) 日期 (1-31)
第四個(gè)參數(shù) 月份?。?-12)
第五個(gè)參數(shù) 星期?。?-6)//0代表星期天
30 20 * * * 就表示每天晚上八點(diǎn)半 執(zhí)行后面的指令(php /path/your.php)
在晚上八點(diǎn)半的時(shí)候,php果然被執(zhí)行了。
這種語(yǔ)法很靈活,其實(shí)不但可以配置,每天固定時(shí)刻執(zhí)行。
還可以配置從哪個(gè)時(shí)間段內(nèi),每隔多長(zhǎng)時(shí)間執(zhí)行一次。
jenkins的任務(wù)也是用這種方法來(lái)配置的。
處理任務(wù)間的沖突
后面,還需要加一些比較頻繁的任務(wù),比如1分鐘1次的。
忽然想起一個(gè)問(wèn)題,如果超過(guò)1分鐘上次任務(wù)還沒(méi)完成怎么辦?
別急人家早就處理了。
引用一下別人的文章(crontab 解決周期內(nèi)未執(zhí)行完重復(fù)執(zhí)行):
利用 flock(FreeBSD lockf,CentOS下為 flock),在腳本執(zhí)行前先檢測(cè)能否獲取某個(gè)文件鎖,以防止腳本運(yùn)行沖突。
格式:
flock [-sxun][-w #] fd#
flock [-sxon][-w #] file [-c] command
選項(xiàng):
-s, --shared: 獲得一個(gè)共享鎖
-x, --exclusive: 獲得一個(gè)獨(dú)占鎖
-u, --unlock: 移除一個(gè)鎖,腳本執(zhí)行完會(huì)自動(dòng)丟棄鎖
-n, --nonblock: 如果沒(méi)有立即獲得鎖,直接失敗而不是等待
-w, --timeout: 如果沒(méi)有立即獲得鎖,等待指定時(shí)間
-o, --close: 在運(yùn)行命令前關(guān)閉文件的描述符號(hào)。用于如果命令產(chǎn)生子進(jìn)程時(shí)會(huì)不受鎖的管控
-c, --command: 在shell中運(yùn)行一個(gè)單獨(dú)的命令
-h, --help 顯示幫助
-V, --version: 顯示版本
鎖類型:
共享鎖:多個(gè)進(jìn)程可以使用同一把鎖,常被用作讀共享鎖
獨(dú)占鎖:同時(shí)只允許一個(gè)進(jìn)程使用,又稱排他鎖,寫(xiě)鎖。
這里我們需要同時(shí)只允許一個(gè)進(jìn)程使用,所以使用獨(dú)占鎖。
修改后的定時(shí)任務(wù)如下:
*/1 * * * * flock -xn /tmp/test.lock -c 'php /home/phachon/cron/test.php' >> /home/phachon/cron/cron.log'
參考:
Linux定時(shí)任務(wù)系統(tǒng) Cron
crontab 解決周期內(nèi)未執(zhí)行完重復(fù)執(zhí)行