栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

如何向flask添加后台线程?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何向flask添加后台线程?

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

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

import threadingimport atexitfrom flask import FlaskPOOL_TIME = 5 #Seconds# variables that are accessible from anywherecommonDataStruct = {}# lock to control access to variabledataLock = threading.Lock()# thread handleryourThread = 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 appapp = create_app()     

从Gunicorn调用它,如下所示:

gunicorn -b 0.0.0.0:5000 --log-config log.conf --pid=app.pid myfile:app


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/369904.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号