技術と本について書くブログ

技術と本について書くblog。技術メモなど雑記を書いているblog。

macのLaunchAgentsを使ってcronのように定期実行をする

ファイルの確認

$ cd ~/Library/LaunchAgents/
$ plutil -lint hoge.plist
hoge.plist: OK

ファイルの中身

<?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>hogehoge</string>
    <key>ProgramArguments</key>
    <array>
        <string>/bin/sh</string>
        <string>/Users/hoge.sh</string>
    </array>
    <key>StartCalendarInterval</key>
    <dict>
        <key>Hour</key>
        <integer>12</integer>
        <key>Minute</key>
        <integer>10</integer>
    </dict>
    <key>StandardOutPath</key>
    <string>/Users/hoge/hoge.out</string>
    <key>StandardErrorPath</key>
    <string>/Users/hoge/hoge.err</string>
</dict>
</plist>

びょうに一回

<key>StartInterval</key>
<integer>10</integer>

登録

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

登録解除

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

登録されているもの一覧

grepで絞ってます

$ launchctl list | grep hoge

注意点

パスが原因でうまくいかない場合 ・シェルの中やコマンドは絶対パスで書く ・以下のように一度カレントに移動巣用にシェルを変更

#!/bin/sh
cd `dirname $0`

・plistにPATHを追加

参考

https://dev.classmethod.jp/tool/mac-launch-agents/

http://macwiki.osdn.jp/wiki/index.php/%E3%82%B3%E3%83%9E%E3%83%B3%E3%83%89/launchctl