How to run a ruby shell script that shows some information, then asks for input and goes background?

97 Views Asked by At

I have a ruby shell script that I want to run on background. However, before going to background I need to ask for an user input.

Is it possible? How can it be achieved?

Thanks in advance!

2

There are 2 best solutions below

0
On BEST ANSWER

Here's a simple example:

def do_stuff(input)
  puts "Input received: #{input}"
  sleep 10
end

print "Enter input value: "
input = gets
pid = fork { do_stuff(input) }
puts "test.rb started, pid: #{pid}"
Process.detach pid

Note the use of fork to start a new process, and detach to allow the subprocess to continue running while the main process exits.

Some platforms (Windows) don't support fork.

0
On

It's definitely possible, My understanding is that non-essential features are pushed to background jobs to alleviate some processing burden for the user experience. I'm doing something along these lines right now but not activated by the user.

You have to ask some questions first I think: Does the process give user feedback in real time (not a good use case for a background job)? How many jobs can one expect to be running simultaneously? How will it interfere or operate with production workers (like unicorn spawn)? What happens if the background jobs fail? Are they processing high priority information? These questions guided me to figure out what to leverage how/when to monitor and whether or not I want it triggered by user input vs on boot vs etc.

Anyway, I would suggest using: http://sidekiq.org/ , It seems to be winner amongst a lot of developers. I would probably implement it by accepting the parameters in the controller and instantiating the worker class (as you can see in sidekiqs documentation) inside a controller method. That worker class will run your ruby shell script probably with Runner like the question here? Runner in Ruby on Rails

You can even trigger them off a model (like emailing after user creation) or what have you.

Another frequently used gem is https://github.com/collectiveidea/delayed_job . I am personally using https://github.com/javan/whenever to activate rake tasks (as cron jobs) when deploying to production. Thats doesn't seem very relevant to you though.

For future questions of this broad nature you should provide some more information on the jobs requirements, such like answering some of the questions in the second paragraph. What are you using for? Do the parameters trigger different scripts? What rails version are you using? Is it used on production or development?