fluffy
fluffy

Reputation: 5314

Flask and watchdog: multiple threads starting

I am writing an application using Flask which monitors a filesystem for updates and logs them. My startup sequence (in debug mode) is:

  1. Create Flask application object
  2. Start Watchdog
  3. Start the application

When running in debug mode, the application automatically restarts with werkzeug's fsevents reloader, which is normal; however, this restart does not terminate the first watchdog thread, and so at this point there is a second watchdog thread, causing every filesystem event to be duplicated.

This doesn't occur in production, but it is impacting my debugging and makes me worry that I am doing something wrong with starting up watchdog. Is there something I should be doing in order to make watchdog exit cleanly, or some way to prevent it from starting up a second time?

Also, when the application does restart due to a code edit, the second watchdog thread does restart correctly; it is only the first watchdog that starts before the initial reload that doesn't shut down on reload.

Upvotes: 0

Views: 1680

Answers (1)

fluffy
fluffy

Reputation: 5314

Rather than starting the background thread before the application starts, it is cleaner and safer to start the thread using app.before_first_request. The downside to this is that the background thread won't start up until the first request comes in.

Upvotes: 1

Related Questions