handlename's blog

コード片など

時間がかかるコマンドを実行した後に通知する

テストとか、ファイルのアップロードとか、 時間のかかるコマンドが終わったら通知してほしい。

rsync heavy.tar.gz remote:/path/to/dist && <終わったら実行する処理>

みたいにしてもいいけど、やっぱり自動で通知してほしい。 zshにはhookというものがあるので、これを使えば何とかなりそう。

で、なんとかしてみたのが以下。

使うときは、 .zshrc に次のように書く。

source /path/to/notify.sh

# 秒数。これ以上時間がかかったら通知する
notify_threshold=30

# コマンド実行後に呼ばれる関数
function notify_notify {
    `curl https://im.kayac.com/api/post/*** -s -d message="done: $notify_prev_command" > /dev/null`
    ecoh "-- notified --"
}

TODO!!

  • 通知関数(notify_notify)に実行したコマンドを渡したい。どうやって取るの…? 取り方教えていただきました。追記参照。
  • lesstail など、開きっぱなしにするコマンドを終了した時にも通知されてしまう。 通知しないコマンドリストを用意して、それに含まれるなら通知しないようにする?

追記 2013-02-02 19:26

@sugyan さんに TTYIDLE という変数を教えてもらった。

man zshall によると、

TTYIDLE <S>
        The idle time of the tty associated with the shell in seconds or -1 if there is no such tty.

もうこれでいいんじゃないの。

追記 2013-02-04 10:51

@kcrt さんに REPORTTIME という変数を教えてもらった。

再び man zshall によると、

REPORTTIME
        If nonnegative, commands whose combined user and system execution times (measured in seconds) are greater than this value have timing statistics printed for them.

こういうふうに秒数を入れておくと、

REPORTTIME=10

その秒数以上コマンド実行に時間がかかった時に 自動で time を付けて実行したことにしてくれる。

$ cpanm Mouse

...

cpanm Mouse  18.26s user 3.51s system 94% cpu 23.116 total

これは便利。

追記 2013-02-08 20:33

@peccul さんにコマンドのとり方を教えてもらった。 gist&サンプルに反映済み。