stopping a python windows service

Benjamin Niemann pink at odahoda.de
Tue Aug 16 18:25:38 EDT 2005


DK wrote:

> i was able to successfully create a windows service using py2exe. it
> polls a website periodically and logs it to a file. this is done using
> a function that does an infinite loop with periodic "sleeps".
> 
> my question is...
> 
> what's the best way to stop this service gracefully?
> 
> when try to stop it from the services applet from control panel, it
> takes forever and then gives me an error.
> 
> currently, the only way i am able to stop it is using the task manager
> and killing the process.

Windows services generally use two threads: one to do the work and one to
listen for messages from the
whatever-the-component-is-called-to-control-services.
When the message thread received a 'stop' message, it should inform the
worker thread to shut down, e.g. using threading.Event. So your worker
should regularily check for the shutdown event, e.g.:

while not shutdownEvent.isset():
    pollWebsite()

    for i in xrange(1800):
        if shutdownEvent.isset():
            break
        time.sleep(1)

But if you get the 'stop' message while the worker thread is in
pollWebsite() and the webserver is sloooow, you'll still have a significant
delay... To avoid this, you would need a http client based on select() that
allows you to check shutdownEvent.isset() at certain intervals - instead of
urlopen which just blocks.


-- 
Benjamin Niemann
Email: pink at odahoda dot de
WWW: http://www.odahoda.de/



More information about the Python-list mailing list