daremkd
daremkd

Reputation: 8424

Do certain operations for x seconds and then exit

Is there some block in Ruby that will allow me to put anything in that code, say 5 methods, which take a variable amount of time to complete. The block should stop executing the code inside it as soon as 5 seconds pass. I know Timeout enables something like this, but would prefer something that doesn't raise an exception in case the timeout passed for performance reasons.

Upvotes: 0

Views: 44

Answers (1)

tckmn
tckmn

Reputation: 59283

Try creating a Thread and then killing it after a specified amount of time:

t = Thread.new {
  sleep 1
  puts 'after 1'
  sleep 2
  puts 'after 2'
  sleep 3
  puts 'after 3'
  sleep 4
  puts 'after 4'
}

sleep 5
t.kill

Output:

after 1
after 2

Upvotes: 1

Related Questions