Here is my version with file locking for rake rails tasks.
Put this in your rake task file (in the namespace so that it does not match other rake tasks):
def cron_lock(name) path = Rails.root.join('tmp', 'cron', "#{name}.lock") mkdir_p path.dirname unless path.dirname.directory? file = path.open('w') return if file.flock(File::LOCK_EX | File::LOCK_NB) == false yield end
using:
cron_lock 'namespace_task_name' do
full example:
namespace :service do def cron_lock(name) path = Rails.root.join('tmp', 'cron', "#{name}.lock") mkdir_p path.dirname unless path.dirname.directory? file = path.open('w') return if file.flock(File::LOCK_EX | File::LOCK_NB) == false yield end desc 'description' task cleaning: :environment do cron_lock 'service_cleaning' do # your code end end end
source share