我正在使用python中的调度模块运行一个函数,该函数每5分钟更新一次mysql数据库。
database_update_function.py
def update_aqi():
query = db.select([Aqi.id, Aqi.City])
result = db.engine.execute(query).fetchall()
for each_city in result:
current_city = each_city[1]
current_id = each_city[0]
aqi_response = get_aqi(current_city)
returned_aqi_data = aqi_response['data']['aqi']
returned_time = aqi_response['data']['time']['s']
update_this = Aqi.query.filter_by(id=current_id).first()
update_this.Aqi = returned_aqi_data
update_this.time = returned_time
db.session.commit()
return "updated time at ...."以及用于调度此操作的函数
def dbUpdate():
schedule.every(5).minutes.do(update_aqi)
While True:
schedule.run_pending()
time.sleep(1)
pass我试着在我的app.py被调用时运行这个函数,但是它必须等待5分钟,然后才能呈现主页。
我还尝试将dbUpdate()函数插入到
@app.route("/")
def index():
"""Return the homepage."""
dbUpdate()
return render_template("index.html")仍然必须等待,所以我尝试插入到我的另一个路由,但它都延迟了该路由必须做的事情。哪里是最好的插入位置,因此它只是从后面运行,而不会干扰?
发布于 2019-07-30 19:34:18
1)数据库级别-在MySQL中,您可以创建以定义的时间间隔运行的EVENT。more here
2)您可以使用类似于Celery的东西,这是一个异步任务队列。
https://stackoverflow.com/questions/57261971
复制相似问题