用途によって配置するフォルダを選ぶ

フォルダ使用法
/System/Library/LaunchDaemonsAppleが提供するシステムデーモン
/System/Library/LaunchAgentsAppleが提供するエージェント。すべてのユーザに対してユーザごとに適用されます
/Library/LaunchDaemonsシステムデーモン
/Library/LaunchAgentsすべてのユーザに対してユーザごとに適用されます
~/Library/LaunchAgentsログイン中のユーザにのみ適用されます

LaunchAgentsはログイン前提、LaunchDaemonsはログインに依存せず実行される。

有効化・無効化

有効化

launchctl load /path/to/your.plist

無効化

launchctl unload /path/to/your.plist

plistのサンプル

20秒毎に実行・ログ出力

  • 標準出力、標準エラー出力をログに出力
  • コマンドのサーチパスを指定
  • ワーキングディレクトを指定
  • /usr/local/bin/node main.jsを実行
<?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.demo.daemon.plist</string>
 
    <key>RunAtLoad</key>
    <true/>
 
    <key>StartInterval</key>
    <integer>20</integer>
 
    <key>StandardErrorPath</key>
    <string>/Users/chet/demo/stderr.log</string>
 
    <key>StandardOutPath</key>
    <string>/Users/chet/demo/stdout.log</string>
 
    <key>EnvironmentVariables</key>
    <dict>
      <key>PATH</key>
      <string><![CDATA[/usr/local/bin:/usr/local/sbin:/usr/bin:/bin:/usr/sbin:/sbin]]></string>
    </dict>
 
    <key>WorkingDirectory</key>
    <string>/Users/chet/demo</string>
 
    <key>ProgramArguments</key>
    <array>
      <string>/usr/local/bin/node</string>
      <string>main.js</string>
    </array>
  </dict>
</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>sample</string>
  <key>Program</key>
  <string>/Users/user_name/script/sample.sh</string>
  <key>StartCalendarInterval</key>
  <dict>
      <key>Minute</key>
      <integer>0</integer>
      <key>Hour</key>
      <integer>3</integer>
  </dict>
  <key>StandardOutPath</key>
  <string>/Users/user_name/script/sample.out</string>
  <key>StandardErrorPath</key>
  <string>/Users/user_name/script/sample.err</string>
</dict>
</plist>

参考にしたページ