how to invoke a method for every second in ruby

会有一股神秘感。 提交于 2019-12-04 13:43:47
Thread.new do
  while true do
    puts Time.now # or call tick function
    sleep 1
  end
end

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