Paul S.
Paul S.

Reputation: 4502

Set timeout for system call in Rails

From Rails, I make a system call to wget:

system("wget", ...)

I want to set a timeout for this call, so that if it takes too long (which is likely to mean too many files downloaded, or a large file downloaded), I want to stop it and return an error to the user, so that my server is not overloaded. How can I do that?

Upvotes: 5

Views: 265

Answers (2)

Sara
Sara

Reputation: 499

In general, try wrapping the call in a SystemTimer. https://rubygems.org/gems/SystemTimer

In your particular case, try system("wget -T #{timeout_in_seconds}")

Upvotes: 1

user24359
user24359

Reputation:

Do you specifically need to run the call in a subshell like that? If not, use timeout and backticks:

require 'timeout'

Timeout.timeout(3) do
  puts `tree /`  # raises an exception, which you can rescue and handle
end

If you do need to run it externally, though, I'd go with something like Subexec

Upvotes: 3

Related Questions