LoginSignup
3
0

More than 5 years have passed since last update.

crontabでtopをバッチモードで定期的に実行する

Posted at

<経緯>
夜間の特定時間帯(毎日少しずつ変動あり)の実行中のJOBのCPU使用率を調べる必要があり、少し苦労したのでメモ。

<問題点>
以下のshellをcrontabで動かすと、出力したログが80バイトくらいでカットされる現象が出て2時間ほど悩んだ。
Terminalから実行すると問題なく出力された。
crontabでの実行時の環境変数の問題と想定されたがなかなかわからず色々ググって解決した。

<結果>
環境変数COLUMNS=197とTERM=vt220を設定。
両方必要かは未確認。

<引数>
CPU%の閾値を設定する。
$ cpu_stress_chk.sh 25.0

<実行方法>
$ crontab -e
*/1 * * * * ~/cpu_stress_chk.sh 25.0

cpu_stress_chk.sh
#!/bin/bash
set -eu
export COLUMNS=197  #表示幅を設定する。
export TERM=vt220   #ターミナルを設定する。
logdir=/logs/xxxxx

hiduke=`date +"%Y%m%d"`
jikan=`date +"%Y%m%d:%H%M"`

threshold=$1       #CPU%の閾値

shname=`/bin/basename $0 ".sh"`
logflnm=$logdir/$shname.$hiduke.log

if [ -f ${logflnm} ]; then
    :
else
    /bin/touch         ${logflnm}
    /bin/chmod 664     ${logflnm}
fi

###------------
###    PROC    
###------------

### COMMAND START
    /usr/bin/top -b -c -n 1 |\
    /bin/grep -E "^ *[0-9]* " |\
    /bin/grep -v -E "\] *$" |\
    /bin/awk  -v "par=${threshold}" '{if ($9 > par) {print $0}}' |\
    /usr/bin/xargs -I{} printf "${jikan}:{}\n" |\
    /bin/sed 's/ *$//g' >> $logflnm
### COMMAND END

exit $?
3
0
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
3
0