开发者

Ruby script as service

开发者 https://www.devze.com 2022-12-22 18:13 出处:网络
Well, the title say it all. I have a ruby script I开发者_JAVA百科 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

Well, the title say it all. I have a ruby script I开发者_JAVA百科 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

Some readings point to creating daemons or cron tasks.

I just need something simple I can call on my box's reboot, and can stop/start whenever I please. my script has an internal sleep call, and runs in "eternal loop"

thanks in advance


I've actually found a much better way of doing that by using ruby scripts.

This is how I did it:

First of all, I installed daemon

gem install daemons

Then I did:

require 'rubygems'
require 'daemons'

pwd  = File.dirname(File.expand_path(__FILE__))
file = pwd + '/runner.rb'

Daemons.run_proc(
   'my_project', # name of daemon
   :log_output => true
 ) do
   exec "ruby #{file}"
end

I then create a file called runner.rb, in which I can call my scripts such as:

require "/var/www/rails/my_project/config/environment"
Post.send('details....')

Daemons is a great gem!


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


RAA - deamons is a verfy useful tool for creating unix daemons from ruby scripts.


From 1.9.x ruby has a built in function:

Process.daemon

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号