Well, the title say it all. I have a ruby script I want running as a service (one I can start and stop) on my Linux box. I was able to find how to do it on Windows here
Posting my answer after more than a decade Original Poster asked the question.
First, let's create a simple ruby script, which will run an infinite loop:
# mydaemon.rb
$stdout.reopen('/home/rmishra/mydaemon.log', 'a')
$stdout.sync = true
loop.with_index do |_, i|
puts i
sleep(3)
end
You can run the script in the background by appending ampersand:
/home/rmishra$ ruby mydaemon.rb &
[1] *pid*
To start this script automatically and restart it whenever it was stopped or crashed, we will create a service.
# mydaemon.service
[Unit]
Description=Simple supervisor
[Service]
User=username
Group=username
WorkingDirectory=/home/username
Restart=always
ExecStart=/usr/bin/ruby mydaemon.rb
[Install]
WantedBy=multi-user.target
Now, let's copy this service file to systemd directory:
sudo cp mydaemon.service /lib/systemd/system -v
Finally, use the enable
command to ensure that the service starts whenever the system boots:
sudo systemctl enable mydaemon.service
The service can be started, stopped or restarted using standard systemd
commands:
sudo systemctl status mydaemon
sudo systemctl start mydaemon
sudo systemctl stop mydaemon
sudo systemctl restart mydaemon
Source