How to schedule a function to run every hour on Flask?

前端 未结 9 2297
我寻月下人不归
我寻月下人不归 2020-11-28 01:10

I have a Flask web hosting with no access to cron command.

How can I execute some Python function every hour?

9条回答
  •  离开以前
    2020-11-28 01:29

    You can use BackgroundScheduler() from APScheduler package (v3.5.3):

    import time
    import atexit
    
    from apscheduler.schedulers.background import BackgroundScheduler
    
    
    def print_date_time():
        print(time.strftime("%A, %d. %B %Y %I:%M:%S %p"))
    
    
    scheduler = BackgroundScheduler()
    scheduler.add_job(func=print_date_time, trigger="interval", seconds=3)
    scheduler.start()
    
    # Shut down the scheduler when exiting the app
    atexit.register(lambda: scheduler.shutdown())
    

    Note that two of these schedulers will be launched when Flask is in debug mode. For more information, check out this question.

提交回复
热议问题