你所能做的就是包装你想要启动的函数
before_first_request
此处找到的装饰器==>
http://flask.pocoo.org/docs/1.0/api/#flask.Flask.before_first_request
但是,除非有人向服务器发出请求,否则它不会启动,但您可以执行以下操作:
import requests
import threading
import time
from flask import Flask
app = Flask(__name__)
@app.before_first_request
def activate_job():
def run_job():
while True:
print("Run recurring task")
time.sleep(3)
thread = threading.Thread(target=run_job)
thread.start()
@app.route("/")
def hello():
return "Hello World!"
def start_runner():
def start_loop():
not_started = True
while not_started:
print('In start loop')
try:
r = requests.get('http://127.0.0.1:5000/')
if r.status_code == 200:
print('Server started, quiting start_loop')
not_started = False
print(r.status_code)
except:
print('Server not yet started')
time.sleep(2)
print('Started runner')
thread = threading.Thread(target=start_loop)
thread.start()
if __name__ == "__main__":
start_runner()
app.run()
https://networklore.com/start-task-with-flask/