Wes Wes -4 years ago 201
Ruby Question

Timeout Module in Ruby - Getting Timer Value

Is there a way to get the "timer" value when running the Timeout Module in Ruby? Say I have this code:

require 'timeout'
status = Timeout::timeout(180) {
sleep(10) until some action
rescue Timeout::Error
puts 'That took too long, exiting...'

So what I want is the overall value of total time that I've waited after each iteration. So after the first 10 seconds, I've waited 10 total seconds, after the 2nd iteration of 10 seconds, I've waited 20 total seconds, and so on.

How can I get that overall value?

Answer Source

Timeout only yields the total seconds so here's an example on how to get that:

Timeout::timeout 5 do |sec|
  puts sec # => prints 5
  sleep 2
  puts sec # => prints 5

So to achieve the "overall" value (time wasted since the beginning) I think you'd have to do something like this:

Timeout::timeout 5 do |sec|
  start = Time.now
  puts (Time.now - start).round # => prints 0
  sleep 2
  puts (Time.now - start).round # => prints 2

I don't know if there's a better way to do this, but this works.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download