Thursday, August 4, 2011

Digg this

Run Any Program as a Windows Service

Microsoft Windows Logo
In this post, we are going to do the unthinkable: run a Java program as a Windows service.  Of course, to do the unthinkable we are going to need a little help from our old friends at Microsoft.  We are going to need the Windows Resource Kit.

The Windows Resource Kit gives us a few cool Windows tools, but for our purpose we only really need srvany.exe.  Srvany.exe is basically just a Windows service that allows us to run any other program as a service.  Since java.exe is also a program, we can use srvany.exe to run a Java program as a Windows service.  I'll demonstrate this by creating a Windows service that launches Selenium RC 1.

To create a service named SeleniumRC1 with srvany.exe, simply drop to the command line (as Administrator if using Vista or Windows 7) and type sc create SeleniumRC1 binPath= "C:\Program Files\Windows Resource Kits\Tools\srvany.exe"
The above command should create a generic service called SeleniumRC1.  If you open up Services under Administrative Tools in the control panel, then you should see an entry for SeleniumRC1.  But we're not done yet.  We haven't told srvany.exe which program to run as a service and Selenium also takes parameters that we have not yet specified.  To do this, open up the registry by executing the command regedit.  Go to the path HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\SeleniumRC1 and you should see all the configuration information for your service (I am actually using WindowsXP, but I think it's the same path for Windows7).

Under your service's path, create a new registry key called Parameters. Now, create 3 seperate String values under the Parameters key that you just created: AppDirectory, Application, and AppParameters.  AppDirectory is the directory that your application will run in (in my case, Selenium RC 1).  Application is the full path to the actual executable that you will run (in my case, java.exe).  AppParameters are the parameters supplied to your app (in my case, the parameters I supply to java.exe).

When you are done filling in the appropriate values, it should look like the image below.

Once you are all done, you should be able to start your service under Services and run it just like it was a Windows service.

*Note: if you want to run a program that runs from the command line (like Selenium) make sure under the Log On tab in the service that Allow service to interact with desktop is checked.

There you have it.  You can now run any program as a Windows service.


Phil T said...

Yea, nice and cheap. Worked for us until we upgraded to this wrapper:

Rafael A P Nascimento said...

Neat. But how do I code this??

Clayton Long said...

You don't really code anything. It's really just some registry updates.

Post a Comment