Wednesday, September 12, 2007

Run your Java program as an NT service

Thomas Boerkel has contributed some mappings and code to the JNA project to facilitate access to Windows' user accounts, registry, and NT services. Included is an abstract class which is capable of installing, uninstalling, and running itself as an NT service. What sets this little gem apart from most available wrappers is that you don't need a Windows executable stub; the complete Windows service API is available to your Java program, including all system events and callbacks.

You can browse the source here. A NetBeans project is included.

I was working on an abstract service class as well but Thomas beat me to completion. Great work, Thomas!

Update: Make sure your classpath and classes are accessible by the local system account, or the service won't be able to start. To see if this is the issue, you can temporarily change the service to start using your user identity; if it works, then the problem is that the local system account doesn't have access.

4 comments:

Unknown said...

Have to admit - this is very impressive and something I've wanted for a while.

I grabbed all the classes - compiled it under Java 6.0 - the service loaded itself into the services list - but then it refused to start.

I'm just using the TestService class.

Any pointers?

technomage said...

a) Make sure your classes are readable by the local system account.
b) Make sure the classpath set in the service launch command makes sense, and is readable by the local system account.

Anonymous said...

It's wonderful, but what if your program already inherits from a class such as JFrame? Can you just instantiate a class that derives from Win32Service? I'm guessing yes.

technomage said...

You can extend the class to do whatever you want. It can instantiate and operate another class, which is probably preferable to trying to merge application logic with the win32 service logic.

Making your application derive from JFrame is poor design.