Sidekiq获取不一致的数据

时间:2016-10-17 06:23:54

标签: ruby-on-rails postgresql sidekiq

class A
  ....
  def something
    if condition
      mark_completed
      // here I can see the object progress is completed
      CompletionStatsWorker.perform_async(self.id)
    end
  end

  def mark_completed
    self.update_attributes!(progress: 'completed')  
  end
end

在工人中:

class CompletionStatsWorker
  include Sidekiq::Worker

  def perform(id)
    obj = A.find(id)
    //here I'm getting the progress of the same object as 'progressing'
  end
end

Sidekiq以某种方式获取旧数据,即使它是在成功的字段更新后触发的。我可以看到对象updated_at与实际updated_at值不同。请帮忙

1 个答案:

答案 0 :(得分:2)

可能会发生这种情况,因为sidekiq的工作速度比提交给数据库的速度快,您应该将CompletionStatsWorker.perform_async(self.id)添加到after_commit回调或将方法更改为:

  def something
    if condition
      if mark_completed
        // here I can see the object progress is completed
        CompletionStatsWorker.perform_async(self.id)
      end
    end
  end

看看sidekiq docs