用 before_app_first_request 的钩子,希望 app 首次启动时,开始运行一个每隔 1 小时定时查询最新数据的任务。结果发现这个任务每隔 1 小时去查询最新的数据,通过 flask_sqlalchemy 初始化之后的工厂模式,查询到的数据都是一样的。如下:
def async_cron_task(app): with app.app_context(): while True: new_user = User.query.order_by(User.reg_time.desc()).first() print('New User: ', new_user.id) time.sleep(3600) def cron_task(): app = current_app._get_current_object() thr = Thread(target=async_cron_task, args=[app]) thr.start() return thr 但是,如果把数据库写成硬连接,就可以查到最新数据:
db=MySQLdb.connect(host='localhost',port=3306,user='xxx',passwd='xxx',db='xxx',charset='utf8') cursor=db.cursor() 由于原生 SQL 查询语句太复杂了,希望用 SQLAlchemy 的方式连接数据库,要怎么样才能定时查到新数据呢?
