launchctl定時任務

最近做個一個定時任務的golang程序,需要每10分鐘運行一次,使用了launchctl,整理了一篇文章方便記憶。

一、plist文件

launchctl是根據plist文件的內容來執行任務的。

plist又根據存放的目錄不同而啓動的時機不同,如下:

~/Library/LaunchAgents 由用戶自己定義的任務項
/Library/LaunchAgents 由管理員爲用戶定義的任務項
/Library/LaunchDaemons 由管理員定義的守護進程任務項
/System/Library/LaunchAgents 由Mac OS X爲用戶定義的任務項
/System/Library/LaunchDaemons 由Mac OS X定義的守護進程任務項

/Library/LaunchAgents爲例,在/Library/LaunchAgents目錄下創建com.demo.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>
  <!-- Label唯一的標識 -->
  <key>Label</key>
  <string>com.demo.plist</string>
  <!-- <key>Program</key>
  <string>/Users/xxx/go/bin/pachong</string> -->
  <!-- 指定要運行的腳本 -->
  <key>ProgramArguments</key>
  <array>
    <string>/Users/xxx/go/bin/pachong</string>
  </array>
  <!-- 指定要運行的時間 -->
  <!-- <key>StartCalendarInterval</key>
        <dict>
            <key>Minute</key>
            <integer>00</integer>

            <key>Hour</key>
            <integer>8</integer>

            <key>Day</key>
            <integer>1</integer>
        </dict> -->
  <!-- 指定要運行的時間 -->
  <key>StartInterval</key>
  <integer>600</integer>
<!-- 標準輸出文件 -->
<key>StandardOutPath</key>
<string>/Users/x x x/go/src/pachong/run.log</string>
<!-- 標準錯誤輸出文件,錯誤日誌 -->
<key>StandardErrorPath</key>
<string>/Users/xxx/go/src/pachong/run.err</string>
</dict>
</plist>
  • Label: 任務的唯一標識
  • ProgramArguments: 命令語句, 第一個
  • Program: 要運行的程序, 如果省略該參數,ProgramArguments的第一個數據作爲運行程序
  • StartInterval: 時間隔間,單位秒
  • StartCalendarInterval: 運行的時間,與StartInterval只能使用其中一個
  • StandardOutPath: 標準輸出文件
  • StandardErrorPath: 錯誤輸出文件

啓動命令

plist文件編寫好之後,先加載plist文件,

launchctl load -w com.demo.plist

-w會覆蓋掉plist文件中無效的部分

刪除任務

launchctl unload -w com.demo.plist

開始任務

立即執行任務,即使時間沒到

launchctl start  com.demo.plist

結束任務

launchctl stop   com.demo.plist

工具

推薦一款launchctl邊界工具LaunchControl

在這裏插入圖片描述

  • 左邊可以看到腳本的狀態
  • 有錯誤時可以點擊修復腳本
  • 可視化編輯plist文件
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章