LoginSignup
24
32

More than 5 years have passed since last update.

OSXでスクリプトを自動実行する方法

Last updated at Posted at 2016-07-23

実行環境
OS:OS X EI Capitan(10.11.5)

1.Launchdとは

launchdはデーモン、アプリケーション、プロセス、スクリプトの起動・停止・管理を行う、オープンソースのサービス管理フレームワークである。

wikiより。Linuxでcronにあたるのかな。

2.サンプルのスクリプトを用意

まず、実行するサンプルのスクリプトを用意します。
今の時間をテキストファイルに保存してスクリプトです。

sample.script
#!/bin/bash

#日付をテキストファイルに保存
cd ~/Desktop
date >> sample.txt

3.launchd.plistを用意

実行するファイル名、実行するタイミングなどを記載した設定ファイルを用意します。以下サンプルです。

sample.time.record.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.time.record</string>
  <!--フルパスで指定-->
 <key>ProgramArguments</key>
   <array>
     <string>/Users/username/Desktop/sample.sh</
string>
   </array>
 <key>StartInterval</key>
   <integer>60</integer>
 <key>RunAtLoad</key>
   <true/>
 <key>ExitTimeout</key>
   <integer>300</integer>
</dict>
</plist>

keyについては以下を参考にしました。
http://tweeeety.hateblo.jp/entry/2015/01/06/215425

key名 説明
Label launchd のジョブの名前。慣例?でファイル名もLabel.plistという名前がいいぽい
ProgramArguments 実行するプログラムとオプションや引数をarrayノードで指定
RunAtLoad trueの場合はlaunchd に launchd.plist がロードされたタイミングで起動
StandardOutPath 標準出力ログの場所。指定がないと/var/log/system.log
StandardErrorPath 標準エラーログの場所。
StartCalendarInterval 実行日時のカレンダー指定
StartInterval カレンダー指定ではなくインターバル指定したいときはこちらを使用

3.launchdへの定期実行の登録/取消と確認

設定ファイルができたら、以下の手順で設定ファイルを反映させます。

①作成しいたファイルを以下のディレクトリに保存
~/Library/LaunchAgents/

②Terminalで作成したファイルを読込
$ launchctl load sample.time.record.plist

③ちゃんと実行されているか確認
$ lauchctl list | grep 'sample'

テキストファイルに1分ごとに時間が記録されていたら成功です。
$ cat ~/Desktop/sample.txt

スケジュールを止めるときはunloadします
$ launchctl unload sample.time.record.plist

設定ファイルを更新した場合は、一度unloadして、再度loadしてください。

参考URL

24
32
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
24
32