As noted in the comments on this question, all that is required for it to work is that you join the stream:
def repeat_every(interval, &block)
loop do
start_time = Time.now
Thread.new(&block).join
elapsed = Time.now - start_time
sleep([interval - elapsed, 0].max)
end
end
repeat_every(5) do
puts Time.now.to_i
end
...
However, as it sits, there is no reason to use threads for code in the question:
def repeat_every(interval)
loop do
start_time = Time.now
yield
elapsed = Time.now - start_time
sleep([interval - elapsed, 0].max)
end
end
repeat_every(5) do
puts Time.now.to_i
end
Now, if you want, this is a thread that does something at intervals, so that the main program can do something else, then you end the whole loop in the thread.
def repeat_every(interval)
Thread.new do
loop do
start_time = Time.now
yield
elapsed = Time.now - start_time
sleep([interval - elapsed, 0].max)
end
end
end
thread = repeat_every(5) do
puts Time.now.to_i
end
puts "Doing other stuff..."
thread.join