我正在使用Flask + Apache + mod_wsgi构建一个Web服务器。我需要在我的web服务器中启动后台线程,以便定期执行一些操作。一切都很好,应用程序启动和线程工作,但我不能加入它。以下是一些代码片段:
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
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()
所以,在app.log
我只看到'应用已启动'。
也许,还有另一种方法可以在apache和wsgi shutdown上加入我的线程,而不仅仅是使用atexit
模块。
答案 0 :(得分:0)
了解它是如何完成的:
在mod_wsgi下使用copy mytable
FROM 's3://mybucket/2016/*'
CREDENTIALS 'aws_access_key_id=<>;aws_secret_access_key=<>'
json 's3://mybucket/jsonpaths.json'
模块是触发进程关闭操作的唯一方法。