当然是要用gem安装win32-service了,要选mswin的版本。
要注意几点:
都使用绝对路径
要把错误捕获,不要随意抛出
记录好日志,windows service不好调
重定向标准输出和错误输出
以下是将安装,删除和运行服务混在一起,可以将控制与服务分开。
略作解释
这个类就是运行服务的主体,必须从Win32::Daemon继承下来。Daemon是一个用C写的类。可以看一下daemon.txt有详细的解释。
以下是创建服务,win32-service 0.5.2是这样写的,0.6有所简化。
重定向标准输出和标准错误,要使用绝对路径,在后台服务进程里不能使用标准输出和错误。
安装好服务后,使用的办法跟普通windows服务一样。
要注意几点:
都使用绝对路径
要把错误捕获,不要随意抛出
记录好日志,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服务一样。