At times you want to run a block of code, say every 5 seconds. How do you do that? Here is how:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
def every_n_seconds(n)
  loop do
    start_time = Time.now
    yield
    time_left = n - (start_time - Time.now)
    sleep(time_left)
  end
end

every_n_seconds(5) { puts "#{Time.now.strftime("%dth, %B %H:%M:%S (%Z)")}: Wake up!"}

/ 06th, October 12:05:25 (NPT): Wake up!
/ 06th, October 12:05:30 (NPT): Wake up!
/ 06th, October 12:05:35 (NPT): Wake up!
/ 06th, October 12:05:40 (NPT): Wake up!