LoginSignup
7
7

More than 5 years have passed since last update.

Rakeタスク実行時、プロセス起動数を確認して排他制御する

Posted at

例えばシェルでやるならこうだけど、rubyで完結させたい。
(シェルスクリプトからrakeを実行したらいいだけだけどメンドクサイ。)

do_something.sh
#!/bin/sh

# プロセス起動確認
isAlivePs=`ps -ef | grep "do_something" | grep -v grep | wc -l`
if [ $isAlivePs = 0 ]; then
  # プロセスが起動していなければ実行
  echo "DO SOMETHING"
else
  # プロセスが起動していた場合は終了
  echo `date` ALREDY RUNNING PROCESS
fi

exit 0

Rakeタスク内でのプロセス数確認する。

scheduler.rake
task :do_something => :environment do
  puts "[#{Time.now.strftime("%Y/%m/%d %H:%M:%S")}] Do something..."

  # プロセス起動確認
  is_alived_ps=`ps -ef | grep "do_something" | grep -v grep | wc -l`
  is_alived_ps_cnt = is_alived_ps.to_i

  # プロセス数 2以下の場合のみ実行
  if is_alived_ps_cnt<=2
    Rails.logger.info("Do something")
  else
    Rails.logger.info("Skip do something")
  end
end
7
7
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
7
7