LoginSignup
30
30

More than 5 years have passed since last update.

cronの重複実行を防ぐちょっとした処理

Posted at

cron処理で、メール送信のような普通にやると冪等性がない、またはなにかしらの理由で同時に二度やりたくない処理をする場合があると思います。

その場合

module CronHelper
  def process_already_exists?(task_name)
     process_count = `ps -ef | grep #{task_name} | grep -v grep | wc -l`.to_i
     process_count > 1
  end
end

のようにprocessの数を見て、すでにあるかどうかをruby側から見れるようにして

require "#{Rails.root}/app/helpers/cron_helper"
include CronHelper

namespace :cron do
  namespace :rake_name do

    task :greet do |task|
      next if process_already_exists?(task.name)

      p 'Hello World!!'
    end

  end
end

のようにrakeタスクに入れれば防げます。

参考

30
30
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
30
30