【问题标题】:Code is unreacheable due to scheduler while loop python flask由于调度程序while循环python烧瓶,代码无法访问
【发布时间】:2022-01-13 07:52:57
【问题描述】:

我正在尝试运行一个调度程序,我的索引函数将在每 1 分钟内运行。我正在使用烧瓶和 postgresql。但是在运行烧瓶运行之后 app.run() 未执行。这是代码:

 def index():
        connection = db.engine.connect(close_with_result=True)
        print('first')
    
        sql = text("""delete from user""")
        print('done')
        connection.execute(sql)
    
        connection = db.engine.connect(close_with_result=True)
    
        sql = text("""select * from user where name='a' or name='b'""")
        connection.execute(sql)
        connection.close()
        
 schedule.every(1).minutes.do(index)
 while True:
       schedule.run_pending()
       time.sleep(1)
    # scheduler wait for 1 second
    
 if __name__ == "__main__":
       app.run()

但似乎这段代码无法访问:

if __name__ == "__main__":
    app.run()

因为这部分代码:

while True:
        schedule.run_pending()
        time.sleep(1)
    # scheduler wait for 1 second

为什么它不起作用?

【问题讨论】:

    标签: python postgresql


    【解决方案1】:

    我认为您不能在使用 __main__ 函数的同一范围内运行阻塞循环。

    我会说你要么创建一个线程来在后台运行带有阻塞循环的调度程序,要么你可以使用APScheduler。

    from apscheduler.schedulers.background import BackgroundScheduler
        
    
    def index():
        connection = db.engine.connect(close_with_result=True)
        print('first')
    
        sql = text("""delete from user""")
        print('done')
        connection.execute(sql)
    
        connection = db.engine.connect(close_with_result=True)
    
        sql = text("""select * from user where name='a' or name='b'""")
        connection.execute(sql)
        connection.close()
    
    scheduler = BackgroundScheduler()
    scheduler.add_job(func=index, trigger="interval", seconds=60)
    scheduler.start()
    
    if __name__ == "__main__":
        app.run()
    

    【讨论】:

    • 调度程序应该在我运行flask run 命令后每 1 分钟运行一次。但不知何故,调度程序无法按照您建议的方法运行。但app.run 有效
    • 当你说它不起作用时,你的意思是它永远不会调用index 方法?我会做一个简单的测试,尝试将秒数降低到 1 秒,然后使用 index 方法在终端上打印一些内容,以验证设置是否正确完成。我自己用index 方法创建了一个基本的flask 应用程序,该方法可以简单地打印,并且调度程序设置为1 秒,这对我有用。
    • 是的,它没有调用索引方法。我做了你提到的所有这些。可能是某种设置问题。
    • 是的,不看完整代码就很难说。在这里你有我正在谈论的代码的basic example,也许将它与你的代码进行比较或尝试运行它。
    猜你喜欢
    • 1970-01-01
    • 2020-03-08
    • 2020-02-05
    • 2021-04-01
    • 2017-10-18
    • 2018-03-21
    • 2014-01-22
    • 2020-11-16
    • 1970-01-01
    相关资源
    最近更新 更多