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

2021-07-11 11:26:52 +08:00
 miniyao

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

4444 次点击
所在节点    Python
43 条回复
fansfans
2021-07-15 09:19:05 +08:00
其实这个和 celery 、apscheduler 好像没什么关联、应该是 session 的上下文使用的是同一个、导致的脏读、但是在接口中进行了 commit 不应该出现这种情况才对、也许可以通过自己创建 session 解决 db_session = sessionmaker(bind=db.engine)()
nicolaz
2021-07-15 17:38:02 +08:00
```python
def set_interval(interval):
def decorator(function):
def wrapper(*args, **kwargs):
stopped = threading.Event()

def loop(): # executed in another thread
while not stopped.wait(interval): # until stopped
function(*args, **kwargs)

t = threading.Thread(target=loop)
t.daemon = True # stop if the program exits
t.start()
return stopped

return wrapper

return decorator


@set_interval(60*60)
def do_something():
pass
```
seven123
2021-07-29 09:35:44 +08:00
celery 的确有时候会出现一些诡异问题,直接用 apscheduler 把

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/788811

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX