Lito26
Lito26

Reputation: 11

How do I Schedule timed events in python Flask?

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.

Upvotes: 1

Views: 2120

Answers (1)

lee-pai-long
lee-pai-long

Reputation: 2292

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.

Upvotes: 3

Related Questions