方法1
進入根目錄
cd/
通過終端打開Finder的根目錄
open/
touch test.sh
vim test.sh
點擊esc鍵,然后輸:wq來保存退出
linux應該都有crontab,沒有的話可以安裝一下:
brew install vixie-cron
brew install crontabs:
vixie-cron軟件包是cron的主程序;
crontabs軟件包是用來安裝、卸裝、或列舉用來驅動 cron 守護進程的表格的程序。
方法2:
使用蘋果的Schedule jobs using launchd設置定時任務。需要寫一個plist文件,描述任務的動作、間隔的時間、日志輸出等參數。
我創建一個plist文件com.hanlingzhi.cron.meican.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>Disabled</key>
<false/>
<key>KeepAlive</key>
<true/>
<key>Label</key>
<string>com.caoyujiao.crib.meican</string>
<key>ProgramArguments</key>
<array>
<string>/usr/bin/php</string>
<string>/Users/caoyujiao/Desktop/IQIYI/tvOS/my.sh</string>
</array>
<key>RunAtLoad</key>
<true/>
<key>StandardErrorPath</key>
<string>/Users/caoyujiao/Desktop/IQIYI/tvOS/stderr</string>
<key>StandardOutPath</key>
<string>/Users/caoyujiao/Desktop/IQIYI/tvOS/stdout</string>
<key>StartCalendarInterval</key>
<dict>
<key>Hour</key>
<integer>0</integer>
<key>Minute</key>
<integer>1</integer>
</dict>
</dict>
</plist>
然后將plist文件放在/Users/hanlingzhi/Library/LaunchAgents,你的用戶目錄下,然后執行launchctl load plist就可以啟動了。
launchctl load -w com.caoyujiao.crib.meican.plist 加載
launchctl unload -w com.caoyujiao.crib.meican.plist 卸載
- 加載后,終端文案會在stdout文件中顯示
- 錯誤信息顯示在stderr文件里面
plist腳本存放路徑為/Library/LaunchDaemons或用戶目錄/Library/LaunchAgents,其區別是后一個路徑的腳本當用戶登陸系統后才會被執行,前一個只要系統啟動了,哪怕用戶不登陸系統也會被執行。
系統定義了幾個位置來存放任務列表
~/Library/LaunchAgents 由用戶自己定義的任務項
/Library/LaunchAgents 由管理員為用戶定義的任務項
/Library/LaunchDaemons 由管理員定義的守護進程任務項
/System/Library/LaunchAgents 由Mac OS X為用戶定義的任務項
/System/Library/LaunchDaemons 由Mac OS X定義的守護進程任務項
可以通過兩種方式來設置腳本的執行時間。一個是使用StartInterval,它指定腳本每間隔多長時間(單位:秒)執行一次;另外一個使用StartCalendarInterval,它可以指定腳本在多少分鐘、小時、天、星期幾、月時間上執行,類似如crontab的中的設置。
launchctl的命令使用大家看一下幫助文檔。
由于操作還是比較復雜,為了幫助快速執行,寫了個shell快速拷貝新的plist并完成服務重啟
總結一下
雖然plist的設置會復雜很多。但是當前在mac os還是傾向于推薦使用Plist的方法,crontab已不推薦使用。
兩者的區別:
1、plist可以設置到秒,而crontab只能到分鐘。
2、plist可以同時應用于Mac OS/Iphone。
3、plist對于MAC上系統交互的操作更支持(我就出現過用crontab設置,運行時出現execution error: 不允許用戶交互。 (-1713)的錯誤)