把ruby程序安装成windows服务

本文介绍如何使用gem安装win32-service,并详细说明了在Windows环境下配置服务的过程,包括服务的安装、删除及运行等操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

当然是要用gem安装win32-service了,要选mswin的版本。

要注意几点:
都使用绝对路径
要把错误捕获,不要随意抛出
记录好日志,windows service不好调
重定向标准输出和错误输出

以下是将安装,删除和运行服务混在一起,可以将控制与服务分开。

LOG_FILE = File.join(File.expand_path(File.dirname(__FILE__)),"../log/win32.log")
begin

require "rubygems"
require "win32/service"
require 'rbconfig'
include Config

require File.join(File.expand_path(File.dirname(__FILE__)),"../lib/robot.rb")

include Win32

SERVICE_NAME="win32robot"
SERVICE_DISPLAYNAME="robot service for win32"
if ARGV[0]=="install"
svc=Service.new
svc.create_service do |s|
s.service_name=SERVICE_NAME
s.display_name=SERVICE_DISPLAYNAME

s.binary_path_name=File.join(CONFIG['bindir'], 'ruby').tr('/', '\\')+" "+File.expand_path($0)
s.dependencies = []
end
svc.close
puts SERVICE_NAME+" is installed"
elsif ARGV[0]=='delete'
if Service.status(SERVICE_NAME).current_state=="running"
Service.stop(SERVICE_NAME)
end
Service.delete(SERVICE_NAME)
puts SERVICE_NAME+" is deleted"
else
if ENV["HOMEDRIVE"]!=nil
puts <<STRING_END
Options:
install -- install service for windows
delete -- delete service
STRING_END
else
#it's wrapper class
class RobotDaemon <Win32::Daemon
def service_init
# Give the service time to get everything initialized and running,
# before we enter the service_main function.
STDOUT.reopen(File.join(File.expand_path(File.dirname(__FILE__)),"../log/stdout.log"))
STDERR.reopen(File.join(File.expand_path(File.dirname(__FILE__)),"../log/stderr.log"))
Robot.init_all()
# sleep 10
end

def service_main
while state == RUNNING
sleep 1
end
end
end
RobotDaemon.new.mainloop
end
end

rescue Exception => err
File.open(LOG_FILE, 'a+')do |fh|
fh.puts 'robot failure: ' + err
err.backtrace.each(){|e| fh.puts "#{e}"}
end
raise
end



略作解释

class RobotDaemon <Win32::Daemon

这个类就是运行服务的主体,必须从Win32::Daemon继承下来。Daemon是一个用C写的类。可以看一下daemon.txt有详细的解释。

以下是创建服务,win32-service 0.5.2是这样写的,0.6有所简化。

svc=Service.new
svc.create_service do |s|
s.service_name=SERVICE_NAME
s.display_name=SERVICE_DISPLAYNAME

s.binary_path_name=File.join(CONFIG['bindir'], 'ruby').tr('/', '\\')+" "+File.expand_path($0)
s.dependencies = []
end
svc.close


重定向标准输出和标准错误,要使用绝对路径,在后台服务进程里不能使用标准输出和错误。

STDOUT.reopen(File.join(File.expand_path(File.dirname(__FILE__)),"../log/stdout.log"))
STDERR.reopen(File.join(File.expand_path(File.dirname(__FILE__)),"../log/stderr.log"))



安装好服务后,使用的办法跟普通windows服务一样。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值