在哪里放置计划的功能来更新数据库,以免干扰?

时间:2019-07-29 22:07:58

标签: python flask scheduler schedule

我正在使用python中的schedule模块运行一个每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")

仍然需要等待,因此我尝试将其插入到其他路由中,但这都会延迟该路由的执行时间。最好的插入位置在哪里,因此它会从后面跑过去并且永不干涉?

1 个答案:

答案 0 :(得分:0)

1)数据库级别-在MySQL中,您可以创建以定义的间隔运行的EVENTmore here

2)您可以使用Celery之类的东西,它是一个异步任务队列。

相关问题