Run Ruby Script in the Background

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



Leave a reply



Submit