Create Java Application to run as a Windows Servic

2019-07-13 05:32发布

i want to create a Windows Service which runs my Java-Application.

This was no problem by using

sc.exe create myService binPath= "java -jar C:\to\my\service.jar"

When I try to start my created service i get this response:

Error 1053: The service did not respond to the start or control request in a timely fashion

Unfortunately it seems my Program didn't respond to the Windows Service that it is running.

How can I communicate to the Windows-Service that my Programm runs?

I tried NSSM which worked great. But I don't want to use another thirdparty app. When I searched for answers I always see that most people use Java Service Wrapper.

How to structure my Java-Code to accept messages from the Windows-Services?

Here is i.e. a simple example of a time-printing programm which i want to run as a service. What do I have to do?

package tst;

import java.util.Date;

public class Tester
{

    public static void main(String[] args)
    {
        Thread thread = new Thread()
        {

            public void run()
            {
                long start = System.currentTimeMillis();
                long end = start + 20 * 1000;

                while (System.currentTimeMillis() < end)
                {
                    Date date = new Date();
                    System.out.println("Time: " + date.toString());

                    try
                    {
                        Thread.sleep(5000);
                    }
                    catch (Exception e)
                    {
                        e.printStackTrace();
                    }
                }

            }
        };
        thread.start();
    }
}

1条回答
Emotional °昔
2楼-- · 2019-07-13 05:59

Unless your application implements the interface required to interact with the Windows Service Control Manager (SCM), you will not be able to start, stop or manipulate your application as a service. Your only option is to use a service wrapper like NSSM, JSW or even Microsoft's old but still functional Srvany utility.

查看更多
登录 后发表回答