coreybutler / node-windows

Windows support for Node.JS scripts (daemons, eventlog, UAC, etc).
Other
2.79k stars 358 forks source link

Service doesn't start immediately after install #218

Closed AshishShanker closed 4 years ago

AshishShanker commented 6 years ago

Let's say I setup a Service object appropriately, and I have the following code:

const svc = new Service({...});
svc.on('install', () => { svc.start(); });
svc.on('start', () => { console.log('Service Started'); });
svc.install();

When I run this script, I get Service Started on the console, but Windows Services MMC shows the service installed but not started. If I manually started the service, it comes up without errors.

However, the following installs and starts the service without errors:

const svc = new Service({...});
svc.on('install', () => { setTimeout(() => { svc.start();}, 10000); });
svc.on('start', () => { console.log('Service Started'); });
svc.install();

The 10s delay is not an arbitrary value. I tried lower numbers as well, and it appears 10s is the lowest value that lets me install and start without errors. That said, it is clearly a function of my machine's current state, so I would really prefer to not have to choose such hardcoded values.

I do notice a sleep() function within node-windows/lib/daemon.js to apparently address this very issue. However, the delay appears to be hardcoded to 2 second, which apparently is not enough delay.

Any thoughts on how to address this issue? Instead of a hardcoded sleep would it make sense to do a sc query ${Service.name} to confirm that the service did get installed correctly, before emitting the 'install' event? (obviously, not accounting for platforms other than Windows)

dustingraham commented 5 years ago

I've found a similar issue when trying to use svc.on('stop', () => { svc.start(); }); needing the delay in order for the start to be successful.

I will say the install callback to svc.start works for me without the delay. Also, on the device I'm testing with, a 2000 ms delay for the stop/start works.

coreybutler commented 4 years ago

The upstream winsw utility sometimes has delays that node-windows has no real way of being able to detect. Unfortunately, the sc command isn't installed on all versions of Windows, so that's not a robust enough option. I could see potentially making it a configuration option. I'm closing this. If anyone wants the sleep to be a config option, submit a PR.