madokaのブログ

勉強したことのoutput先として使ってます。内容はpythonがらみが多いかもです。

macでcron的なことをする

macで定期実行はcronではなく、launchdがおすすめ

macでもcronは使えるらしいが、launchdを利用することが推奨されているらしいので、launchdで書きます。

今回動かすコマンド

$ /bin/sh path/to/test1.sh

のコマンドを動かしてもらいます。 念のためfull pathで/bin/sh指定しました。

コード

<?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>test1</string>
    <key>ProgramArguments</key>
    <array>
        <string>/bin/sh</string>
        <string>/path/to/test1.sh</string>
    </array>
    <key>StartCalendarInterval</key>
    <dict>
         <key>Hour</key>
         <integer>7</integer>
         <key>Minute</key>
         <integer>10</integer>
    </dict>
    <key>StandardOutPath</key>
    <string>/path/to/out.log</string>
    <key>StandardErrorPath</key>
    <string>/path/to/err.log</string>
</dict>
</plist>

ファイルの置き場所

用途 Directory
ユーザーごとの設定 ~/Library/LaunchAgents/<Label>.plist
全てのユーザーの設定 /Library/LaunchAgents/<Label>.plist
システム共通設定 /Library/LaunchDaemons/<Label>.plist
  • LaunchAgents : ログインしているときに動くもの
  • LaunchDaemons : ログインしてなくても動くもの

ファイル名の<Label>とファイル中の<Label>を一致させる。今回の場合はtest1

コマンドの指定

今回動かしてもらおうと思っていたコマンドを空白区切で配列としてProgramArgumentsをkeyにして記入する。

<key>ProgramArguments</key>
<array>
    <string>/bin/sh</string>
    <string>/path/to/test1.sh</string>
</array>

イベントのタイミング

今回は毎日同じ時間にプログラムを動かして欲しいので、時間指定しました。

<key>StartCalendarInterval</key>
<dict>
    <key>Hour</key>
    <integer>7</integer>
    <key>Minute</key>
    <integer>10</integer>
</dict>

数秒ごとにプログラム実行も可能。その場合はStartCalendarIntervalの代わりにStartIntervalを利用する。この時の単位は秒です。

<key>StartInterval</key>
<integer>300</integer>

その他にもファイル監視をすることもできるようです。 下記urlに詳しく書いてあります。

Creating Launch Daemons and Agents

登録と解除

ユーザーがログインしている時に動かしたいので、pathは~/Library/LaunchAgents/test1.plistにしました。

登録する

$  launchctl load ~/Library/LaunchAgents/test1.plist

解除する

$  launchctl unload ~/Library/LaunchAgents/test1.plist