Ruby on Rails - 延迟工作的奇怪行为逻辑

时间:2012-04-19 16:13:55

标签: ruby-on-rails ruby ruby-on-rails-3 delayed-job

我正在通过tobi执行delayed_job,当我运行delayed_job但是fbLikes计数都是错误的,并且每次添加一个公司时它似乎都会递增。不确定逻辑错误。我之前测试过的fbLikes方法有效(在我改为delayed_job之前) 不知道“1”来自哪里......

[输出]

coca-cola
http://www.cocacola.com
Likes: 1  <--- Not sure why the fbLikes is 1 and it increment with second company fbLikes is 2 and so on...

[Worker(host:aname.local pid:1400)] Starting job worker
[Worker(host:aname.local pid:1400)] CountJob completed after 0.7893
[Worker(host:aname.local pid:1400)] 1 jobs processed at 1.1885 j/s, 0 failed ...
  

我在Model中运行delayed_job并尝试运行   算facebook喜欢

这是我的代码。 [LIB / count_rb.job]

require 'net/http'
    class CountJob< Struct.new(:fbid)

def perform 
    uri = URI("http://graph.facebook.com/#{fbid}")
    data = Net::HTTP.get(uri)
    return JSON.parse(data)['likes']
end
end

[公司模式]

before_save :fb_likes
def fb_likes            
    self.fbLikes = Delayed::Job.enqueue(CountJob.new(self.fbId))
end 

1 个答案:

答案 0 :(得分:0)

问题来自

before_save :fb_likes  
def fb_likes  
  self.fbLikes = Delayed::Job.enqueue(CountJob.new(self.fbId))  
end

enqueue方法不会返回运行CountJob的结果。我相信它将返回作业是否成功排队,当你将其保存到fb_likes值时,它会在作业成功排队时评估为1。

你应该在delayed_job运行的作业中设置fbLikes,而不是因为入队调用。

before_save :enqueue_fb_likes  
def fb_likes  
  Delayed::Job.enqueue(CountJob.new(self.fbId))  
end

您在CountJob类中的perform方法应该可以使用模型ID来查找并访问fbId和fbLikes属性,而不是仅使用fbId。

class CountJob< Struct.new(:id)

def perform
  company = Company.find(id)
  uri = URI("http://graph.facebook.com/#{company.fbid}")
  data = Net::HTTP.get(uri)
  company.fbLikes = JSON.parse(data)['likes']
  company.save
end