title: How to stop flask from reloading the code twice?
body: <p>The question was asked, but I have another issue.</p>
  
  <p>I've tried:</p>
  
  <pre><code>app.run(use_reloader=False)
  </code></pre>
  
  <p>As in:</p>
  
  <pre><code>from flask import Flask, render_template
  from scheduler import *
  from regions import regions
  
  app = Flask(__name__)
  
  @app.route("/")
  def index():
      return render_template("index.html", regions=regions)
  
  if __name__ == "__main__":
      app.run(use_debugger=False, use_reloader=False)
  </code></pre>
  
  <p>But nothing happens. It just keeps on reloading.</p>
  
  <pre><code>~/workspace/finalproject/weather/ $ flask run
  * Serving Flask app "sync"
  * Forcing debug mode off
  * Running on http://ide50-artemnikitin27ed.cs50.io:8080/ (Press CTRL+C to quit)
  * Restarting with stat
  INFO:apscheduler.scheduler:Scheduler started
  DEBUG:apscheduler.scheduler:Looking for jobs to run
  DEBUG:apscheduler.scheduler:No jobs; waiting until a job is added
  INFO:apscheduler.scheduler:Scheduler started
  DEBUG:apscheduler.scheduler:Looking for jobs to run
  DEBUG:apscheduler.scheduler:No jobs; waiting until a job is added
  </code></pre>
  
  <p>I've even turned off the debug mode, but still the reloader keeps running the code twice at startup.</p>
  
  <p>I need this in order to stop the Apscheduler running twice, which works perfectly, expect for this issue.</p>
  
  <p>I'll be very grateful for any help!</p>
  
  <p><strong>SOLUTION:</strong></p>
  
  <p>For disabling the reloader, if you use <code>flask run</code> execute <code>flask run --no-reload</code> instead as in the answer <a href="https://stackoverflow.com/a/25504196/8882620">https://stackoverflow.com/a/25504196/8882620</a></p>
  
  <p>For solving the problem without blocking the reloader, place the apscheduler settings in a function and wrap it with <code>@app.before_first_request</code>:</p>
  
  <pre><code>@app.before_first_request
  def before_first_request():
     scheduler = BackgroundScheduler()
     scheduler.start()
     scheduler.add_job(
     func=historical,
     trigger=CronTrigger(hour=12, minute=12),
        id='save_weather',
        name='Archive avg temp for current day',
        replace_existing=True)
  
     # Shut down the scheduler when exiting the app
     atexit.register(lambda: scheduler.shutdown())
  </code></pre>