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

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

    You could try using APScheduler's BackgroundScheduler to integrate interval job into your Flask app. Below is the example that uses blueprint and app factory (init.py) :

    from datetime import datetime
    
    # import BackgroundScheduler
    from apscheduler.schedulers.background import BackgroundScheduler
    from flask import Flask
    
    from webapp.models.main import db 
    from webapp.controllers.main import main_blueprint    
    
    # define the job
    def hello_job():
        print('Hello Job! The time is: %s' % datetime.now())
    
    def create_app(object_name):
        app = Flask(__name__)
        app.config.from_object(object_name)
        db.init_app(app)
        app.register_blueprint(main_blueprint)
        # init BackgroundScheduler job
        scheduler = BackgroundScheduler()
        # in your case you could change seconds to hours
        scheduler.add_job(hello_job, trigger='interval', seconds=3)
        scheduler.start()
    
        try:
            # To keep the main thread alive
            return app
        except:
            # shutdown if app occurs except 
            scheduler.shutdown()
    

    Hope it helps :)

    Ref :

    1. https://github.com/agronholm/apscheduler/blob/master/examples/schedulers/background.py

提交回复
热议问题