1

I'm executing a command with in ruby using open3, and Im setting a timeout using the safe_timeout gem (because of known issues with timeout reported here)

The code I have is very simple:

SafeTimeout.timeout(t) do
  stdout, stdeerr, status = Open3.capture3(cmd)
  @output = stdout
  @result = status.exitstatus
  @pid = status.pid
  @timeout = t
end

The caveat here is that I only want to run this within the timeout block if t is defined.

Obviously I can use an if statement but then I'd have duplicate stuff and it doesn't feel very "ruby-like" to me.

Is there a nice way to do something like:

if t
  timeout.do
    command
  end
else
  command_without_timeout
end

?

1 Answer 1

4

You can use a Proc - the reified version of a Ruby code block. Put your command in the proc, and then either pass the proc to the timeout method (using the & operator to pass it as a block instead of a normal parameter) or else just call it directly. Example:

block = proc do
  # this is the code I want to run
  # with or without the timeout 
  stdout, stdeerr, status = Open3.capture3(cmd)
  @output = stdout
  @result = status.exitstatus
  @pid = status.pid
  @timeout = t
end

if t then
  SafeTimeout.timeout(t, &block)
else
  block.call
end
Sign up to request clarification or add additional context in comments.

4 Comments

Awesome! This is what I ended up with. Thanks for the quick reply!
Quick question actually. I also want to get the duration of the block to determine how long it took to execute. When running block.call I can just do the following: startTime = Time.now block.call @duration = Time.now - startTime However doesn't seem clear to me how to do this with &block - is there a way?
Why can't you do it with the timeout version, too? startTime = Time.now; if t then SafeTimeout.timeout(t,&block) else block.call end; @duration = Time.now - startTime
Ignore me, it was a stupid question anyway. I know how long it took because I set a timeout for it to end. D'oh

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.