반응형
필요한에 배경을 추가해야합니까?
판매를 시험해보기 위해 작은 게임 서버를 작성 하느라 바쁘다. 이 게임은 REST를 통해 사용자에게 API를 노출합니다. 사용자가 작업을 수행하고 데이터를 쿼리하는 것은 쉽지만 app.run () 루프 외부에서 "게임 세계"를 서비스하여 게임 엔터티 등을 업데이트하고 싶습니다. 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
순수 스레드 또는 셀러리 대기열 (플라스크 셀러리는 더 이상 필요하지 않음)을 사용하는 것 외에도 flask-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()
참고 URL : https://stackoverflow.com/questions/14384739/how-can-i-add-a-background-thread-to-flask
반응형
'ProgramingTip' 카테고리의 다른 글
Qt“비공개 양성소 :”이것은 무엇입니까? (0) | 2020.11.02 |
---|---|
Node.js + express.js + passport.js : 서버 재시작 사이에 인증 유지 (0) | 2020.11.02 |
C #의 암호 (0) | 2020.11.02 |
코드 흐름을하는 도구 (C / C ++) (0) | 2020.11.02 |
"다중 대상 패턴"Makefile 오류 (0) | 2020.11.02 |