Created
August 2, 2020 09:43
-
-
Save kndo/e0217d1cb7563685f751ce0872a32a01 to your computer and use it in GitHub Desktop.
Example of flask + apscheduler factory pattern
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# app.py | |
from flask import Flask | |
from .scheduler import register_scheduler # Assuming in same directory as app.py | |
def create_app(): | |
app = Flask(__name__) | |
register_scheduler(app) | |
return app | |
# scheduler.py | |
from flask_apscheduler import APScheduler | |
def query_db(): | |
return | |
def register_scheduler(app): | |
DEV_JOBS = [ | |
{ | |
'id': 'query_db', | |
'func': query_db, | |
'trigger': 'cron', | |
'hour': '*', # Run every hour | |
}, | |
# some dev jobs | |
] | |
STAGING_JOBS = [ | |
# some staging jobs | |
] | |
PROD_JOBS = [ | |
# some prod jobs | |
] | |
flask_env = app.config.get('FLASK_ENV') | |
if flask_env == 'develop': | |
app.config.update(JOBS=DEV_JOBS) | |
elif flask_env == 'staging': | |
app.config.update(JOBS=STAGING_JOBS) | |
elif flask_env == 'production': | |
app.config.update(JOBS=PROD_JOBS) | |
scheduler = APScheduler() # Use default scheduler: BackgroundScheduler | |
scheduler.init_app(app) | |
scheduler.start() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Note: JOBS can also be defined in your config file directly.