1

我正在使用 rufus 调度程序同时启动许多预定的作业。我想要该代码中的一个变量,当它在一段时间后再次运行时,它只能用于该计划的作业。

我如何为每个计划的作业维护一个变量?

4

1 回答 1

1

有多种方法可以做到这一点。我将详细介绍其中的一些,从丑陋到某种优雅。

使用 rufus-scheduler 2.0.23 ( https://rubygems.org/gems/rufus-scheduler )在 Debian GNU/Linux 7 上针对 Ruby 1.9.3p392 测试的解决方案。

您可以使用全局变量:

require 'rufus-scheduler'

scheduler = Rufus::Scheduler.start_new

scheduler.every '1s' do
  $counter0 ||= 0
  $counter0 += 1
  p [ :c0, $counter0 ]
end
scheduler.every '1s' do
  $counter1 ||= 0
  $counter1 += 1
  p [ :c0, $counter1 ]
end

scheduler.join

或者您可以将作业变量集中在一个全局变量中(注意:这不是线程安全的):

require 'rufus-scheduler'

scheduler = Rufus::Scheduler.start_new

$job_vars = {}

scheduler.every '1s' do |job|
  ($job_vars[job.object_id] ||= {})['counter'] ||= 0
  $job_vars[job.object_id]['counter'] += 1
  p [ job.job_id, job.object_id, $job_vars[job.object_id]['counter'] ]
end
scheduler.every '1.5s' do |job|
  ($job_vars[job.object_id] ||= {})['counter'] ||= 0
  $job_vars[job.object_id]['counter'] += 1
  p [ job.job_id, job.object_id, $job_vars[job.object_id]['counter'] ]
end

scheduler.join

更进一步,只是为了好玩(但仍然不是线程安全的):

require 'rufus-scheduler'

scheduler = Rufus::Scheduler.start_new

$job_vars = {}
job = lambda { |job|
  ($job_vars[job.object_id] ||= {})['counter'] ||= 0
  $job_vars[job.object_id]['counter'] += 1
  p [ job.job_id, job.object_id, $job_vars[job.object_id]['counter'] ]
}

scheduler.every '1s', &job
scheduler.every '1.5s', &job

scheduler.join

最后,您可以将 #vars 添加到 Job 类:

require 'rufus-scheduler'

class Rufus::Scheduler::Job
  def vars
    @vars ||= {}
  end
end

scheduler = Rufus::Scheduler.start_new

scheduler.every '1s' do |job|
  job.vars['counter'] = (job.vars['counter'] || 0) + 1
  p [ job.job_id, job.object_id, job.vars['counter'] ]
end
scheduler.every '1.5s' do |job|
  job.vars['counter'] = (job.vars['counter'] || 0) + 1
  p [ job.job_id, job.object_id, job.vars['counter'] ]
end

scheduler.join

这是我喜欢的解决方案。我打算在 rufus-scheduler 3.0 ( https://github.com/jmettraux/rufus-scheduler ) 中为 Job 添加一个类似的变量包。

您还可以将变量放在其他地方并使用 job_id / job.object_id 作为检索它的键(就像第一个代码片段一样)。

我希望这将有所帮助。

于 2013-08-13T21:07:12.753 回答