延迟工作超时

时间:2014-10-03 13:05:34

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

我有一些可能会运行更长时间的代码。但是,如果确实如此,我想杀死它,这就是我现在正在做的事情:

def perform
    Timeout.timeout(ENV['JOB_TIMEOUT'].to_i, Exceptions::WorkerTimeout) { do_perform }
  end

私人   def do_perform     ......一些代码......   端

JOB_TIMEOUT是一个环境变量,其值为10.seconds。我有报告说这仍然不能阻止我的工作运行时间更长。

有更好的方法吗?

1 个答案:

答案 0 :(得分:2)

我相信delayed_job会执行一些异常处理voodoo并进行多次重试等,更不用说我认为 do_perform将立即返回,并且该作业将像往常一样在另一个线程中继续。我认为更好的方法是在工作者中进行流量控制

def perform
  # A nil timeout will continue with no timeout, protect against unset ENV
  timeout = (ENV['JOB_TIMEOUT'] || 10).to_i

  do_stuff

  begin
  Timeout.timeout(timeout) { do_long_running_stuff }
  rescue Timeout::Error
    clean_up_after_self
    notify_business_logic_of_failure
  end
end

这会奏效。额外的好处是不会将delayed_job与业务逻辑紧密耦合 - 这段代码可以移植到任何其他未经修改的作业排队系统。