Run ruby script in background without using screen
I think the most basic solution would be nohup
:
nohup myscript &> /dev/null &
Run Ruby script in the background
Have a look at screen
which is a command-line utility. Start it with
screen
You will get a new shell which is detached. Start your script there with
ruby whatever.rb
And watch it run. Then hit Ctrl-A Ctrl-D and you should be back at your original shell. You can leave the ssh session now, and the script will continue running. At a later time, login to your box and type
screen -r
and you should be back to the detached shell.
If you use screen more than once, you will have to select the screen session by pid which is not so comfortable. To simplify, you can do
screen -S worker
to start the session and
screen -r worker
to resume it.
How can I trigger a shell script and run in background (async) in Ruby?
@TanzeebKhalili's answer works, but you might consider Kernel.spawn(), which doesn't wait for the process to return:
pid = spawn("./test.sh")
Process.detach(pid)
Note that, according to the documentation, whether you use spawn()
or manually fork()
and system()
, you should grab the PID and either Process.detach()
or Process.wait()
before exiting.
Regarding redirecting standard error and output, that's easy with spawn()
:
pid = spawn("./test.sh", :out => "test.out", :err => "test.err")
Process.detach(pid)
Running a background ruby script from a php page
You should write a poller in the ruby script that checks the file you write from PHP periodically. There is an issue of concurrency when you are trying to do this: the producer could be writing at the same time the consumer is reading.
I suggest to read and write to DB, so you don't have to worry about it. If you don't want to setup a fully professional DB, you can use SQLite (ruby PHP).
how to check if ruby script is running in background from PHP script?
I don't like the idea but you can do this on linux
exec('ps -A | grep ruby.rb', $output);
not sure what's about other systems.
Related Topics
How to Open Files Relative to Home Directory
How to Rescue Model Transaction and Show the User an Error
Accessing Ruby Class Variables with Class_Eval and Instance_Eval
Rails: Ensure Only One Boolean Field Is Set to True at a Time
Can't Convert Fixnum to String During Rake Db:Create
Sending a Post Request with Net/Http
Binary String Literals in Ruby 2.0
"Ago" Date/Time Functions in Ruby/Rails
How to Filter an Array of Hashes to Get Only the Keys in Another Array
Namespacing Thor Commands in a Standalone Ruby Executable
How to Specify Post Params in a Rails Test
Cleanest Way to Create a Hash from an Array
How to Use Ruby Minitest::Spec with Rails for API Integration Tests