将Ruby程序作为Windows服务运行?
是否可以将ruby应用程序作为Windows服务运行?我看到有一个相关的问题讨论了将Java应用程序作为Windows服务运行,我们如何使用Ruby应用程序来做到这一点?
解决方案
我们可以编写(或者下载)包装器服务。包装程序可以调用ruby.exe执行程序。同样的技巧适用于Java,VB等。
我们应该能够在IronRuby中完成此任务,因为我们将拥有.NET框架。
签出以下库:Win32Utils。我们可以创建一个简单的服务,我们可以在闲暇时启动/停止/重新启动。我目前正在使用它来管理Windows托管的Rails应用程序的Mongrel实例,并且可以完美地工作。
尝试使用Win32Utils时,确实需要研究文档并仔细研究网络,然后再找到一些简单的工作示例。
这似乎在2008年10月2日生效:
gem install win32服务
更新2012-11-20:
根据https://stackoverflow.com/users/1374569/paul
现在register_bar.rb应该是
Service.create( :service_name => 'some_service', :host => nil, :service_type => Service::WIN32_OWN_PROCESS, :description => 'A custom service I wrote just for fun', :start_type => Service::AUTO_START, :error_control => Service::ERROR_NORMAL, :binary_path_name => 'c:\usr\ruby\bin\rubyw.exe -C c:\tmp\ bar.rb', :load_order_group => 'Network', :dependencies => ['W32Time','Schedule'], :display_name => 'This is some service' )
LOG_FILE = 'C:\test.log' begin require "rubygems" require 'win32/daemon' include Win32 class DemoDaemon < Daemon def service_main while running? sleep 10 File.open("c:\test.log", "a"){ |f| f.puts "Service is running #{Time.now}" } end end def service_stop File.open("c:\test.log", "a"){ |f| f.puts "***Service stopped #{Time.now}" } exit! end end DemoDaemon.mainloop rescue Exception => err File.open(LOG_FILE,'a+'){ |f| f.puts " ***Daemon failure #{Time.now} err=#{err} " } raise end
bar.rb是服务,但我们必须先创建和注册!
这可以通过sc create some_service来完成
但是,如果我们要使用ruby和win32utils,我们应该做一个
require "rubygems" require "win32/service" include Win32 # Create a new service Service.create('some_service', nil, :service_type => Service::WIN32_OWN_PROCESS, :description => 'A custom service I wrote just for fun', :start_type => Service::AUTO_START, :error_control => Service::ERROR_NORMAL, :binary_path_name => 'c:\usr\ruby\bin\rubyw.exe -C c:\tmp\ bar.rb', :load_order_group => 'Network', :dependencies => ['W32Time','Schedule'], :display_name => 'This is some service' )
注意,'c:\ usr \ ruby \ bin \ rubyw.exe -C c:\ tmp \ bar.rb'中的c:\ tmp \ bar.rb之间有一个空格
运行ruby register_bar.rb
现在,我们可以从Windows服务控制面板或者
sc start some_service
并观看c:test.log充满
服务正在运行2008年10月2日星期四22:06:47 +0200
为了简单起见,可以更轻松地删除服务寄存器并创建一个新的寄存器,而不用修改现有的寄存器
require "rubygems" require "win32/service" include Win32 Service.delete("some_service")
归功于人民
http://rubypane.blogspot.com/2008/05/windows-service-using-win32-service-and_29.html
http://rubyforge.org/docman/view.php/85/595/service.html