Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to run an apscheduler job which requires app_context

I have a flask app which needs to run some of the methods as background tasks. I have been trying to use apscheduler. Background tasks which do not require app_context run without issue, however, tasks which do require it always throw an error:

RuntimeError: Working outside of application context.

I have tried various options. 1. I have passed app into the job, and altered all the jobs to accept app as a parameter.

I have tried to force the background task to start an app with the following:

class APScheduler(_BaseAPScheduler):
    def start(self):
        app = create_app()
        apply_config(app)
        with app.app_context():
            super().start()

Both options do not appear to have managed to get app_context. Are there any other ways to force the background task to have app_context?

like image 298
Andrew Gill Avatar asked Oct 20 '25 11:10

Andrew Gill


1 Answers

Try using the Flask-APScheduler extension. It's a convenient wrapper around the apscheduler library.

So for your use case, you would do something like this

from flask_apscheduler import APScheduler

scheduler = APScheduler()

# Then to use a flask context inside a job
def some_job():
    with scheduler.app.app_context():
      #...


like image 123
jpmulongo Avatar answered Oct 23 '25 01:10

jpmulongo