Ruby Timer

I searched for an online example demonstrating a ruby ​​timer and came across the code below. It works as expected, but does it make sense that this simple program uses 30Mo of memory (as shown in the Windows task manager) and too much CPU?

Thank you so much

def time_block
  start_time = Time.now
  Thread.new { yield }
  Time.now - start_time
end

def repeat_every(seconds)
  while true do
    time_spent = time_block { yield } # To handle -ve sleep interaval
    sleep(seconds - time_spent) if time_spent < seconds
  end
end

repeat_every(5) {
}
+5
source share
1 answer

As noted in the comments on this question, all that is required for it to work is that you join the stream:

#!/usr/bin/ruby1.8

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

# => 1266437822
# => 1266437827
# => 1266437832
...

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

# => 1266437911
# => 1266437916
# => 1266437921

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

# => 1266438037
# => Doing other stuff...
# => 1266438042
# => 1266438047
+11

All Articles