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

前端 未结 9 2348
我寻月下人不归
我寻月下人不归 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:32

    I'm a little bit new with the concept of application schedulers, but what I found here for APScheduler v3.3.1 , it's something a little bit different. I believe that for the newest versions, the package structure, class names, etc., have changed, so I'm putting here a fresh solution which I made recently, integrated with a basic Flask application:

    #!/usr/bin/python3
    """ Demonstrating Flask, using APScheduler. """
    
    from apscheduler.schedulers.background import BackgroundScheduler
    from flask import Flask
    
    def sensor():
        """ Function for test purposes. """
        print("Scheduler is alive!")
    
    sched = BackgroundScheduler(daemon=True)
    sched.add_job(sensor,'interval',minutes=60)
    sched.start()
    
    app = Flask(__name__)
    
    @app.route("/home")
    def home():
        """ Function for test purposes. """
        return "Welcome Home :) !"
    
    if __name__ == "__main__":
        app.run()
    

    I'm also leaving this Gist here, if anyone have interest on updates for this example.

    Here are some references, for future readings:

    • APScheduler Doc: https://apscheduler.readthedocs.io/en/latest/
    • daemon=True: https://docs.python.org/3.4/library/threading.html#thread-objects

提交回复
热议问题