I want to test that a process is working so I run:
cmd = "my unix command"
results = `#{cmd}`
How can I add a timeout to the command so that if it takes more than x seconds I can assume that it is not working?
Ruby ships witrh the Timeout module.
require 'timeout'
res = ""
status = Timeout::timeout(5) {res = `#{cmd}`} rescue Timeout::Error
# a bit of experimenting:
res = nil
status = Timeout::timeout(1) {res = `sleep 2`} rescue Timeout::Error
p res # nil
p status # Timeout::Error
res = nil
status = Timeout::timeout(3) {res = `sleep 2`} rescue Timeout::Error
p res # ""
p status # ""
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With