我如何添加一个后台线程来瓶?(How can I add a background thread t

2019-07-18 08:46发布

我忙着写一个小游戏服务器尝试烧瓶中。 本场比赛暴露通过REST给用户的API。 这很容易让用户执行操作和查询数据,但是我想“游戏世界”服务的app.run()循环外面来更新游戏实体等鉴于瓶是如此干净实施,我想看看是否有一个瓶的方式来做到这一点。

Answer 1:

您的其他线程必须从由WSGI服务器调用相同的应用程序来启动。

下面的示例创建后台线程执行每5秒和操纵该也可用来瓶路由功能的数据结构。

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


Answer 2:

除了使用纯螺纹或芹菜队列(注意,瓶,芹菜不再需要),你也可以看看烧瓶,apscheduler:

https://github.com/viniciuschiele/flask-apscheduler

一个简单的例子,从复制https://github.com/viniciuschiele/flask-apscheduler/blob/master/examples/jobs.py :

from flask import Flask
from flask_apscheduler import APScheduler


class Config(object):
    JOBS = [
        {
            'id': 'job1',
            'func': 'jobs:job1',
            'args': (1, 2),
            'trigger': 'interval',
            'seconds': 10
        }
    ]

    SCHEDULER_API_ENABLED = True


def job1(a, b):
    print(str(a) + ' ' + str(b))

if __name__ == '__main__':
    app = Flask(__name__)
    app.config.from_object(Config())

    scheduler = APScheduler()
    # it is also possible to enable the API directly
    # scheduler.api_enabled = True
    scheduler.init_app(app)
    scheduler.start()

    app.run()


文章来源: How can I add a background thread to flask?