Search code examples
pythonrestsubprocesscherrypy

Start a background process upon successful quickstart in cherrypy


I have a REST WebService built on top of cherrypy. The service goes online with the cherrypy.quickstart() call.

I want to start a background process with subprocess.Popen() right after the service goes online. The cherrypy.quickstart() call is blocking. How can I add a callback to start the background process?


Solution

  • If your background task is simple and isn't CPU-bound I would suggest you to use cherrypy.process.plugins.BackgroundTask. It's a thread based solution. Here's an answer with complete example.

    Generally in CherryPy we don't pass callbacks to go along internal components. Instead we use Plugins. CherryPy's own components like session data expiration or request timeout monitors, daemoniser and PID writer and others are Plugins. Plugin's life cycle is bound to the message bus. The FSM diagram illustrates the state changes. In your Plugin you just need to handle some of the states that make sense for your task.

                     O
                     |
                     V
    STOPPING --> STOPPED --> EXITING -> X
       A   A         |
       |    \___     |
       |        \    |
       |         V   V
     STARTED <-- STARTING
    

    This answer has a Plugin example. Also take a look at Managing your process with the CherryPy’s bus by Sylvain Hellegouarch.