6

Flask 中怎样用 while 写一个定时执行的任务?(定时查询最新数据)

 3 years ago
source link: https://www.v2ex.com/t/788811
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

V2EX  ›  Python

Flask 中怎样用 while 写一个定时执行的任务?(定时查询最新数据)

  miniyao · 19 小时 49 分钟前 · 1192 次点击

用 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 的方式连接数据库,要怎么样才能定时查到新数据呢?


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK