Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to use background scheduler with an flask + gunicorn app

I have one scheduler to send message periodically in my flask app. For gunicorn, I defined 10 sync workers and the app create 10 schedulers and send the same message 10 times. Is there any way to only send one message? The code for flask app:

def send_msg():
     # here we send msg

@app.before_first_request
def activate_job():
     scheduler = BackgroundScheduler()
     scheduler.add_job(send_msg, 'interval', minutes=5)
     scheduler.start()
     atexit.register(lamda: scheduler.shutdown())
like image 917
wentzz Avatar asked Sep 12 '25 16:09

wentzz


1 Answers

The 4 workers call the function activate job that's why your message was sent 4 times, I solved the problem by adding the background task in the main function that's called when I run my app and I added with app.app_context(): before the job function in your case

    def send_msg():
        with app.app_context():
            # here we send msg
like image 199
abdelwaheb moalla Avatar answered Sep 14 '25 06:09

abdelwaheb moalla