如何排队rufus-scheduler作业

时间:2017-02-07 19:06:29

标签: ruby rufus-scheduler

我有以下内容:

# myScript.rb

require 'rufus-scheduler'

  def loop
    "hey I am i the loop"
  end 

  def run_schedule(url, count, method, interval)
    puts "running scheduler"

    scheduler = Rufus::Scheduler.new

    scheduler.every interval do

    loop(url, count, method)
    end
  end  

  run_schedule(url, count, method, interval)

我的期望是,当我跑步时:

bundle exec ruby myScript.rb url, count, method, interval

我看到输出到STD的一堆"嘿,我在循环中#34;基于区间。

当我退出命令行提示符并且永远不会看到循环运行时会发生什么。

1 个答案:

答案 0 :(得分:1)

你怎么能指望

def loop
  "hey I am i the loop"
end 

输出任何东西到stdout(不是STD)?它只是返回一个字符串,而不是调用printputs ...

# myScript.rb

require 'rufus-scheduler'

def _loop(u, c, m)
  # "loop" is a bad name, it's a Ruby keyword, so using "_loop" instead
  # it's still a bad name

  p "hey I am i the loop"
  p [ Time.now, [ u, c, m ] ]
    # without p or puts nothing gets to stdout
end

$scheduler = Rufus::Scheduler.new
  # creating a single scheduler for the whole script
  # not creating a new scheduler each time run_schedule is called

def run_schedule(url, count, method, interval)

  #puts "running scheduler"
  #scheduler = Rufus::Scheduler.new
    # commenting out...

  $scheduler.every interval do

    _loop(url, count, method)
  end
end

#run_schedule(url, count, method, interval)
run_schedule('url', 'count', 'method', '3s')

$scheduler.join
  # let the Ruby main thread join the scheduler thread so that
  # the Ruby process does not exit and so scheduling may happen

所以它会:

"hey I am i the loop"
[2017-02-08 06:06:01 +0900, ["url", "count", "method"]]
"hey I am i the loop"
[2017-02-08 06:06:05 +0900, ["url", "count", "method"]]
"hey I am i the loop"
[2017-02-08 06:06:08 +0900, ["url", "count", "method"]]

请注意脚本末尾的$scheduler.join。这可以防止Ruby进程退出。由于该过程不存在,因此其中的线程(在我们的示例中,是rufus-scheduler实例中的线程)生存并完成其工作。您的初始脚本只是退出,正如预期的那样释放所有资源。