how to invoke a method for every second in ruby

送分小仙女□ 提交于 2019-12-21 20:21:15

问题


I wanted to create a stopwatch program in ruby so I googled it and found this SO Q.

But over there, the author calls the tick function with 1000xxx.times. I wanted to know how I can do it using something like (every second).times or for each increment of second do call the tick function.


回答1:


Thread.new do
  while true do
    puts Time.now # or call tick function
    sleep 1
  end
end



回答2:


This function:

def every_so_many_seconds(seconds)
  last_tick = Time.now
  loop do
    sleep 0.1
    if Time.now - last_tick >= seconds
      last_tick += seconds
      yield
    end
  end
end

When used like this:

every_so_many_seconds(1) do
  p Time.now
end

Results in this:

# => 2012-09-20 16:43:35 -0700
# => 2012-09-20 16:43:36 -0700
# => 2012-09-20 16:43:37 -0700

The trick is to sleep for less than a second. That helps to keep you from losing ticks. Note that you cannot guarantee you'll never lose a tick. That's because the operating system cannot guarantee that your unprivileged program gets processor time when it wants it.

Therefore, make sure your clock code does not depend on the block getting called every second. For example, this would be bad:

every_so_many_seconds(1) do
  @time += 1
  display_time(@time)
end

This would be fine:

every_so_many_seconds(1) do
  display_time(Time.now)
end


来源:https://stackoverflow.com/questions/12504940/how-to-invoke-a-method-for-every-second-in-ruby

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!