nvm環境でcronからNode.jsを呼び出す
cron使うとログイン時に設定してくれる環境変数が使えないので、実行できるように手探りで何とかしようという話です。
cron実行下の環境を再現する
素晴らしい記事があったので、これを参考にすれば良いかと。
直接nodeコマンドを使わず、シェルを挟む
nvm
環境下でのnode
コマンドの在処は~/.nvm/v0.10.28/bin/node
などとバージョンが含まれるため、そのまま呼び出すのはよろしくない(バージョンが上がると動かなくなる)。
そこで簡単なシェルを挟む。
簡単なシェル
$ vi test.sh
#!/bin/sh
source ~/.nvm/nvm.sh
if [ -n "$1" ]
then
node "$@" >> test.log
else
node -v
fi
nvm
の環境変数を読み込んで、引数があったらnode
コマンドに渡すだけ。
確認プログラム
$ vi test.js
console.log(new Date(), process.argv[2] + ' node.js');
cron
テスト用に引数を受け取って表示するだけの簡単なプログラム。
実行してみる
$ chmod +x test.sh
$ ./test.sh
./test.sh: 3: ./test.sh: source: not found
しかしエラー。な、なぜに?
$ ls -l /bin/sh
lrwxrwxrwx 1 root root 4 Mar 29 2012 /bin/sh -> dash
Ubuntuの/bin/shの実体はbash
じゃなくてdash
だったのか……
test.sh
$ vi test.sh
#!/bin/bash
...
source
を.
に置き換えれば動きそうなんだけど、今後他にも問題が出ると面倒なので/bin/bash
にしておく。
cronの設定
$ crontab -e
* * * * * ~/test.sh test.js hello
これで、毎分test.logに出力されるはず
結果
$ tail -f test.log
Tue May 27 2014 16:52:01 GMT+0000 (UTC) 'hello node.js'
Tue May 27 2014 16:53:01 GMT+0000 (UTC) 'hello node.js'
Tue May 27 2014 16:54:01 GMT+0000 (UTC) 'hello node.js'
ちゃんと表示された。