I'm sure there is a simple way to do this but I can't seem to find it.
I simply want my ruby program to run all the time, so if it exits or terminates for some reason I want it to automatically re-run.
Any ideas of how to achieve this?
-Thanks
I'm sure there is a simple way to do this but I can't seem to find it.
I simply want my ruby program to run all the time, so if it exits or terminates for some reason I want it to automatically re-run.
Any ideas of how to achieve this?
-Thanks
While you can write this sort of thing yourself, it's probably better to start with a library like daemons and use that to manage your process.
As shown in the README it's pretty simple:
require 'daemons'
Daemons.run('service.rb')
Where service.rb
is the entry point into your main application that you want to keep running.
Your approach of force-restarting the application within the same Ruby process might seem to work, but it's liable to cause chaos later on. What if your program has entered a state where doing anything leads to an exception, and that causes a restart, which immediately triggers a new exception? What if it crashed because the internal state is mangled?
Let it die, restart it cleanly with a supervisor process like Daemons, and you'll be much better off. These supervisors often throttle restarts to avoid pinning your server with thousands of reboots per second if it's having trouble.
The restart logic is properly done for you by the monitor you use in your server (systemd or monit can do that pretty easily but there are many others).
If you are doing a service you don't want it to restart every time because the it will be too costly, the process is held in a event loop that waits for income requests but this is usually done for you in the library you use to handle the protocol, so you write only the handler for the incoming request.