Home > Software engineering >  Code is unreacheable due to scheduler while loop python flask
Code is unreacheable due to scheduler while loop python flask

Time:01-13

I am trying to run a scheduler where in evey 1 min my index function will run.I am using flask and postgresql.But after running flask run app.run() is not executed. This is the code:

 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()

But seems like this bit of code is unreacheable:

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

because of this portion of code:

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

Why its not working?

CodePudding user response:

I don't think you can run a blocking loop in the same scope you use your __main__ function.

I would say that you either create a thread to run the scheduler with the blocker loop in the background or alternatively you could use 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()
  •  Tags:  
  • Related