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

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

    You might want to use some queue mechanism with scheduler like RQ scheduler or something more heavy like Celery (most probably an overkill).

    0 讨论(0)
  • 2020-11-28 01:40

    I've tried using flask instead of a simple apscheduler what you need to install is

    pip3 instal flask_apscheduler

    Below is the sample of my code:

    from flask import Flask
    from flask_apscheduler import APScheduler
    
    app = Flask(__name__)
    scheduler = APScheduler()
    
    def scheduleTask():
        print("This test runs every 3 seconds")
    
    if __name__ == '__main__':
        scheduler.add_job(id = 'Scheduled Task', func=scheduleTask, trigger="interval", seconds=3)
        scheduler.start()
        app.run(host="0.0.0.0")
    
    0 讨论(0)
  • 2020-11-28 01:46

    Another alternative might be to use Flask-APScheduler which plays nicely with Flask, e.g.:

    • Loads scheduler configuration from Flask configuration,
    • Loads job definitions from Flask configuration

    More information here:

    https://pypi.python.org/pypi/Flask-APScheduler

    0 讨论(0)
提交回复
热议问题