mac系統(tǒng)上的定時(shí)任務(wù)用launchctl來管理
先寫要執(zhí)行的腳本run.sh:
#!/bin/bash
echo `date` > $HOME/test_result.log
再寫調(diào)度任務(wù)的plist文件task.plist:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<!-- 名稱涮毫,要全局唯一 -->
<key>Label</key>
<string>com.xyz.test</string>
<!-- 要運(yùn)行的程序配喳, 如果省略這個(gè)選項(xiàng),會(huì)把ProgramArguments的第一個(gè)
元素作為要運(yùn)行的程序 -->
<key>Program</key>
<string>/Users/xyz/test.sh</string>
<!-- 命令座舍, 第一個(gè)為命令馁启,其它為參數(shù)-->
<key>ProgramArguments</key>
<array>
<string>/Users/xyz/test.sh</string>
</array>
<!-- 運(yùn)行時(shí)間 -->
<key>StartCalendarInterval</key>
<dict>
<key>Minute</key>
<integer>10</integer>
<key>Hour</key>
<integer>17</integer>
</dict>
<!-- 標(biāo)準(zhǔn)輸入文件 -->
<key>StandardInPath</key>
<string>/Users/xyz/test-in.log</string>
<!-- 標(biāo)準(zhǔn)輸出文件 -->
<key>StandardOutPath</key>
<string>/Users/xyz/test-out.log</string>
<!-- 標(biāo)準(zhǔn)錯(cuò)誤輸出文件 -->
<key>StandardErrorPath</key>
<string>/Users/xyz/test-err.log</string>
</dict>
</plist>
然后再添加到執(zhí)行列表中
launchctl load task.plist
就可以了。
注意一點(diǎn):系統(tǒng)在自動(dòng)運(yùn)行shell腳本時(shí)是不會(huì)加載任何環(huán)境變量的,所以可能出現(xiàn)自己手工運(yùn)行腳本正常买决,但是在調(diào)度任務(wù)中出錯(cuò)。這種情況需要導(dǎo)入環(huán)境變量來解決吼畏,如果不知道需要導(dǎo)入哪些環(huán)境變量督赤,最簡(jiǎn)單的方法是直接導(dǎo)入所有環(huán)境變量的配置文件,如果使用的shell是bash泻蚊,可以在運(yùn)行腳本中加入如下一句:
source ~/.bashrc
如果執(zhí)行任務(wù)后在錯(cuò)誤日志里出現(xiàn)operation not permitted躲舌,把bash添加到full disk access中,打開Mac系統(tǒng)中的System Preference -> Full Disk Access藕夫,另打開一個(gè)新的finder window孽糖,點(diǎn)擊go,輸入/bin/bash毅贮,把bash拖入到Full Disk Access列表中
plist文件的詳細(xì)內(nèi)容參考: