Cover by Leonard Richardson, Lucas Carlson

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

O'Reilly logo

20.2. Creating a Windows Service

Credit: Bill Froelich

Problem

You want to write a self-contained Ruby program for Windows that performs a task in the background.

Solution

Create a Windows service using the win32-service library, available as the win32-service gem.

Put all the service code below into a Ruby file called rubysvc.rb. It defines a service that watches for the creation of a file c:\findme.txt; if it ever finds that file, it immediately renames it.

The first step is to register the service with Windows. Running ruby rubysrvc.rb register will create the service.

	# rubysrvc.rb
	require 'rubygems'
	require 'win32/service'
	include Win32

	SERVICE_NAME = "RubySvc"
	SERVICE_DISPLAYNAME = "A Ruby Service"
	if ARGV[0] == "register"
	  # Start the service.
	  svc = Service.new
	  svc.create_service do |s|
	    s.service_name = SERVICE_NAME
	    s.display_name = SERVICE_DISPLAYNAME
	    s.binary_path_name = 'C:\InstantRails-1.3\ruby\bin\ruby ' +
	      File.expand_path($0)
	    s.dependencies = []
	  end
	  svc.close
	  puts "Registered Service - " + SERVICE_DISPLAYNAME

When you're all done, you can run rubysrvc.rb stop to stop the service and remove it from Windows:

	elsif ARGV[0] == "delete"
	  # Stop the service.
	  if Service.status(SERVICE_NAME).current_state == "running"
	    Service.stop(SERVICE_NAME)
	  end
	  Service.delete(SERVICE_NAME)
	  puts "Removed Service - " + SERVICE_DISPLAYNAME
	else

If you run rubysrvc.rb with no arguments, nothing will happen, but it will remind you what parameters you can use:

 if ENV["HOMEDRIVE"]!=nil # We are not running ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required