您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

如何向flask添加后台线程?

如何向flask添加后台线程?

你的其他线程必须从WSGI服务器调用的同一应用程序启动。

下面的示例创建一个后台线程,该线程每5秒执行一次,并处理Flask路由函数也可用的数据结构。

import threading
import atexit
from flask import Flask

POOL_TIME = 5 #Seconds

# variables that are accessible from anywhere
commonDataStruct = {}
# lock to control access to variable
dataLock = threading.Lock()
# thread handler
yourThread = threading.Thread()

def create_app():
    app = Flask(__name__)

    def interrupt():
        global yourThread
        yourThread.cancel()

    def doStuff():
        global commonDataStruct
        global yourThread
        with dataLock:
        # Do your stuff with commonDataStruct Here

        # Set the next thread to happen
        yourThread = threading.Timer(POOL_TIME, doStuff, ())
        yourThread.start()   

    def doStuffStart():
        # Do initialisation stuff here
        global yourThread
        # Create your thread
        yourThread = threading.Timer(POOL_TIME, doStuff, ())
        yourThread.start()

    # Initiate
    doStuffStart()
    # When you kill Flask (SIGTERM), clear the trigger for the next thread
    atexit.register(interrupt)
    return app

app = create_app()     

从Gunicorn调用它,如下所示:

gunicorn -b 0.0.0.0:5000 --log-config log.conf --pid=app.pid myfile:app
Python 2022/1/1 18:24:06 有171人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶