Han
Han

Reputation: 5652

Is there a way to write a Ruby loop that runs one iteration for a maximum set amount of time?

I'm looking to create a Ruby (MRI 1.9.3) loop that runs at most for a certain amount of time, and once that time is up it goes to the next iteration of the loop.

For example, this is what I'm hoping to achieve:

timer = Timer.new
while foo
  timer.after 5 do # The loop on foo only gets to run for 5 seconds
    next
  end

  # Do some work here
end

So far, I've found tarcieri's gem called Timers (https://github.com/tarcieri/timers) which is what I'm trying to emulate in the code above, but my implementation doesn't give the behavior I expect, which is for the loop to go to the next iteration after 5 seconds if my work takes longer than that. Any ideas?

Upvotes: 4

Views: 6248

Answers (3)

Erez Rabih
Erez Rabih

Reputation: 15808

require 'timeout'
timeout_in_seconds = 5
while foo
  begin
    Timeout.timeout(timeout_in_seconds) do
      # Do some work here
    end
  rescue Timeout::Error
    next
  end
end

Upvotes: 13

Jordan
Jordan

Reputation: 32552

It's been awhile since I brushed off my Ruby skills, but I believe you can do this with the timeout library.

require 'timeout'

while foo
    Timeout.timeout(5) do
        work()
    end
end

Upvotes: 2

Antony Fuentes
Antony Fuentes

Reputation: 1103

You can also try this:

time = 60
time_start = Time.now
begin      
      time_running = Time.now - time_start
      #You_code_goes_here
end until (time_running.to_i >= time)

That loop will happen until the time_running var is equal or greater than "60".

Upvotes: 0

Related Questions