You can start the scheduler in Flask's before_first_request() decorator, which "registers a function to be run before the first request to this instance of the application".
import time
import atexit
from apscheduler.schedulers.background import BackgroundScheduler
def print_date_time():
print(time.strftime("%A, %d. %B %Y %I:%M:%S %p"))
@app.before_first_request
def init_scheduler():
scheduler = BackgroundScheduler()
scheduler.add_job(func=print_date_time, trigger="interval", seconds=3)
scheduler.start()
# Shut down the scheduler when exiting the app
atexit.register(lambda: scheduler.shutdown())
Note that before_first_request()
will always be called again with the first request after server reload.