Double code execution

I am running Rails 4.2.0 with Ruby 2.0.0. I iterate over the model Production.alland call production.finish!in the .each loop. My end! the method, in the end, removes itself using self.destroy. But each undefined record will be executed twice in a single loop.

def finish!
  self.progress = true
  self.save # that other crontabs can't access me anymore if the crontabs overlap

  if DeliveredProduction.find_by_production_id(self.id)
    # send me a notification, why this object still exists?
  else
    DeliveredProduction.create!(:production_id => self.id) # Each undefined times a get an Exception here because the production_id is already insert!
    # ...
    # do things here
  end
  self.destroy # my debug logs says that each entry was successful deleted
end

Is there a bug in Rails 4.2.0 or Ruby 2.2.0p0? Only after 1-2 days is a single execution performed. This code will be executed by crontab. I also update all Production in an iteration with progress = true, so that later crontabs will not be able to access these objects. My debug log says that the second execution of the same Production occurs after the same time (one second) after a few seconds.

+4
source share
1 answer

after_commit :

after_commit :deliver!, on: :update, if: ->{|me| me.progress}

def finish!
  self.update(progress: true)
end

def deliver!
  DeliveredProduction.create!(:production_id => self.id)
  self.destroy
end

Model#save , . after_commit . after_commit:

"after_commit"

0

Source: https://habr.com/ru/post/1598232/


All Articles