Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run Ruby script in the background

Tags:

ruby

I have a Ruby script that I need to have running all the time in my Linux box. I tried nohup ruby ruby.rb& but it seems it doesn't work.

How can I have the script running in background?

like image 413
donald Avatar asked Jun 17 '11 20:06

donald


2 Answers

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.

like image 136
moritz Avatar answered Oct 17 '22 06:10

moritz


Depending on your needs:

fork do
  Process.setsid
  sleep 5
  puts "In daemon"
end
puts "In control script"

In real life you will have to reopen STDOUT/STDERR.

like image 41
Victor Moroz Avatar answered Oct 17 '22 06:10

Victor Moroz