问题
I have a Flask application that's deployed on a single AWS EC2 instance. In my __init__.py file I've instantiated a BackgroundScheduler with a job scheduled to run at every 1 hour interval. Here's an example of my __init__.py code:
application = Flask(__name__)
app = application
scheduler = BackgroundScheduler()
run_my_jobs = scheduler.add_job(my_job, 'interval', hours=1)
scheduler.start()
I would assume that since the instantiation is done outside of the Flask context, and with only one single instance running on EC2, that my scheduler should only be instantiated once, regardless of how many users are connected to my Flask app throughout the day.
That has generally been the case for the past couple months, however recently in the past couple days I noticed the scheduler has been executing the job almost 2-3 times per hour. While I've been continuing to push code to production, the __init__.py file has remained unchanged so I'm confused as to what are possible reasons to cause multiple instantiations of the scheduler?
回答1:
There are generally two ways this can happen:
- Using more than one worker process
- Putting the code in the module that is your application's entry point and not protecting it with an
if __name__ == '__main__':
block
From your description I assume #1 is not the case, so I'd go for #2.
来源:https://stackoverflow.com/questions/36068887/apscheduler-on-a-single-ec2-instance-getting-called-multiple-times