Search code examples
pythoncherrypy

How to detect if cherrypy is shutting down


I've made a server based on cherrypy but I have a repetitive task which takes a long time (more than a minute) to run. This is all fine until I need to shut down the server, then I am waiting forever for the threads to finish.

I was wondering how you'd detect a cherrypy shutdown inside the client thread so that the thread could abort when the server is shutting down.

I'm after something like this:

class RootServer:
    @cherrypy.expose

    def index(self, **keywords):
        for i in range(0,1000):
            lengthyprocess(i)
            if server_is_shutting_down():
                return

Solution

  • You can inspect the state directly:

    if cherrypy.engine.state != cherrypy.engine.states.STARTED:
        return
    

    Or, you can register a listener on the 'stop' channel:

    class RootServer:
    
        def __init__(self):
            cherrypy.engine.subscribe('start', self.start)
            cherrypy.engine.subscribe('stop', self.stop)
    
        def start(self):
            self.running = True
    
        def stop(self):
            self.running = False
    
        @cherrypy.expose
        def index(self, **keywords):
            for i in range(0,1000):
                lengthyprocess(i)
                if not self.running:
                    return
    

    The latter is especially helpful if you also want to have the lengthyprocess start (or perform some preparation) when the server starts up, rather than upon a request.