-->

WinRun4J - service not stopping

2019-04-14 06:34发布

问题:

I'm using this to install my application as a windows service. Everything works fine except the service does not stop;

@Override
public int serviceMain(String[] strings) throws ServiceException {        

    try {
        System.out.println("BootService: init");
        System.out.println("BootService: service loop start");            
        while (ws.isServiceRunning()) {
            System.out.println("BootService: loop");
            ws.serviceHandler();
        }

        System.out.println("BootService: stopped");       
        return 0;

    } catch (Exception ex) {            
        throw new ServiceException(ex);
    }

}

@Override
public int serviceRequest(int control) throws ServiceException {
    try {
        switch (control) {
            case SERVICE_CONTROL_SHUTDOWN:
            case SERVICE_CONTROL_STOP:
                if (ws!=null) {
                    ws.stopService();
                }
                break;
        }
        return 0;
    } catch (WindowsServiceException ex) {
        throw new ServiceException(ex);
    }
}

My service backend code is stopped by the call to serviceRequest(), which in turn makes the loop in serviceMain() exit. I see the message "BootService: stopped" in my logs, yet the Window Control Panel Services Applet just sits says "Stopping service...", but it never does.

What would stop the service from stopping even though I'm sure it has exited the serviceMain() without error?

回答1:

I don´t know if you could solve it, but I had a simmilar problem and I fixed it by adding a timer that called System.exit(0)

public int serviceMain(String[] args) throws ServiceException {
    while (!shutdown) {
        try {
            if (!myservice.isRunning()) {
                (new Thread(new LaucherRunnable(args))).start();
            }
            Thread.sleep(6000);
        } catch (InterruptedException e) {
        }         
    }
    periodicRunner.stop();
    Timer t = new Timer(1000, new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            System.exit(0);
        }
    });
    t.setRepeats(false);
    t.start();
    return 0;
}


标签: winrun4j