1

I'm working on a flask framework trying to schedule a job that will be triggered in 30 min from lunch and will happen only once.

I tried to work with threading.Timer, But since my job calling a REST request I'm getting RunTimeError: 'working outside of request context' which I just couldn’t solve.

From this thread, I understand that it is not recommended using the threading module on a flask server: How do you schedule timed events in Flask?

So I'm looking for a solution for a timed trigger job (which doesn’t work on intervals).

It looks like APscheduler must be interval based.

I would be grateful for any help.

Community
  • 1
  • 1
Lito26
  • 11
  • 3
  • 1
    Try to use `Celery`. – stamaimer May 17 '17 at 16:12
  • Hey, I think my problem is maybe different, because spawning a new thread without a timer also leads to the same RunTimeError. It seems that when a new thread is created, it doesn't get an app context or a request context. I managed to pass the app context as a parameter to the new thread; however, still there is no request context, and the exception the thrown when it tries to reach a request. Is it possible to generate a request, or should I pass it as well? Thanks :) – Lito26 May 17 '17 at 21:13
  • http://flask.pocoo.org/docs/0.12/patterns/celery/ – stamaimer May 18 '17 at 00:38

1 Answers1

3

The apscheduler add_job method can take a date trigger that will allow you to do what you want.

Pro tips:

If you use apscheduler inside your flask app process, when going into production with a wsgi server like gunicorn or uwsgi you will hand up with your job being run multiple time(one for each flask worker).

When facing this issue the gunicorn --preload option didn't cut it for me.

So:

  • You can use flask-apscheduler with his rest server approach if that suits you.
  • Or separate the apscheduler into a daemon and
    • use uwsgi mules,
    • or keep gunicorn running only the web app and use supervisor(or an equivalent) to start the scheduler daemon.

IMHO the separation of gunicorn/flask and apscheduler into two part and use of supervisor is the cleanest yet not so complex solution.

lee-pai-long
  • 2,147
  • 17
  • 18
  • But separation of gunicorn and background job handled by supervisor is not an option in container. – SerG Mar 07 '20 at 16:20
  • @SerG you're right if we have one container with the all app, but best practice suggest to have one process per container, so I would put the wsgi flask app in one container, and the scheduler in another one. – lee-pai-long Mar 09 '20 at 09:15