2016-10-26

launchdでデーモンやスケジュールタスクを管理する

Linuxだとserviceやcronを使いますが、OSXだとlaunchctlを使うようです。ということで、launchctl(launchd)の使い方を備忘としてまとめました。

基本的な使い方

plistを定義したら、あとは以下のコマンドで読み込むだけ ```bash $ launchctl load {plist file path} ``` launchctlのリロードのサブコマンドはないので、plistのリロードをしたい場合は以下のコマンドで行います。 ```bash $ launchctl unload {plist file path} && launchctl load {plist file path} ``` 以下のコマンドで起動・停止します(RunAtLoadがtrueの場合はロード直後のstartは必要なし) ```bash $ launchctl start {label name} $ launchctl stop {label name} ```

plist

plistの書き方はmanページを見るのが良いです。 ```bash $ man launchd.plist ``` plistファイルはXML形式でLabel, ProgramArgumentsは必須です。ProgramArgumentsの一つ目が実行プログラムで、あとは引数です。標準出力も定義可能。RunAtLoadはlaunchctl loadしたときにstartするかどうかの設定。常に起動させたい系のプログラムであればKeepAliveにtrueをセットすれば、killされても自動的に再起動してくれる。 スケジュールタスクを登録したい場合はStartIntervalやStartScheduleを定義します。

echoデーモン(スケジューラ)

<?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.freedom-man.echo</string>
  <key>ProgramArguments</key>
  <array>
     <string>echo</string>
     <string>Hello World</string>
  </array>
  <key>StandardOutPath</key>
  <string>/path/to/log</string>
  <key>StartInterval</key>
  <integer>20</integer>
  <key>RunAtLoad</key>
  <true/>
 </dict>
</plist>

echoデーモン(常駐)

echo-loop.sh↓

#!/bin/bash

while :
do
  echo $1
  sleep 2
done

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.freedom-man.echo-loop</string>
  <key>ProgramArguments</key>
  <array>
     <string>/Users/xxx/echo-loop.sh</string>
     <string>Hello World</string>
  </array>
  <key>StandardOutPath</key>
  <string>/path/to/log</string>
  <key>RunAtLoad</key>
  <true/>
 </dict>
</plist>

ハマり

10秒以下のStartIntervalの設定がうまくいかない…

→ThrottleIntervalも2にしたらうまく行った

参考URL

このエントリーをはてなブックマークに追加