1

I'm building a web-server using Flask + Apache + mod_wsgi. I need to start a background thread in my web-server in order to do some stuff periodically. Everything fine, app started and thread works, but I can not join it. Below is some code snippets:

.wsgi file

import sys, atexit, logging

logging.basicConfig(filename='app.log', level=logging.INFO, filemode='w')
logging.info('App started')

sys.path.insert(0, '/my/src/dir/with/main.py/')

from main import app, users_manager

@atexit.register
def on_exit_callback():
    logging.info('App will now be shutdowned')
    users_manager.set_shutting_down()
    users_manager.join_thread()

application = app

main.py

from flask import Flask
import logging
from threading import Thread

app = Flask(__name__)

@app.route("/", methods=['GET'])
def home():
   return "OK"

class UsersManager():
    def __init__(self):
        self.users = {}

        self.shutdown_thread = False

        self.my_worker_thread = Thread(target=self.worker_function)
        self.my_worker_thread.start()

    def worker_function(self):
        while self.shutdown_thread is not True:
            # doing my stuff

    def set_shutting_down(self):
        self.shutdown_thread = True

    def join_thread(self):
        logging.info('joining thread')
        if self.my_worker_thread.is_alive():
            logging.info('thread is alive')
            self.my_worker_thread.join()

users_manager = UsersManager()

if __name__ == "__main__":
    app.run()

So, in app.log I see only 'App started'.

Maybe, there are another ways to join my thread on apache and wsgi shutdown, not only using atexit module.

sashadereh
  • 223
  • 1
  • 15

1 Answers1

0

See how it is done in:

Under mod_wsgi using atexit module is the only way to trigger actions on process shutdown.

Graham Dumpleton
  • 57,726
  • 6
  • 119
  • 134
  • 1
    I put `atexit` handler to `wsgi.py` file, but it brought no result. I don't see `App will now be shutdowned` in debug log. I tried to put this handler to `main.py` - still no effect. – sashadereh Apr 13 '16 at 19:11
  • Put your updated code in a gist so can see if you actually changed it to match what was documented. How your code worked was not the same. Also set LogLevel to into in Apache and gather the Apache error logs from time when process should have shutdown. There are certain things which can cause a process not to shutdown properly but simply be killed if you have other issues with your code. – Graham Dumpleton Apr 13 '16 at 20:47