pythonflaskroutesapscheduler

How can I get BackgroundScheduler to update variable in Flask route?


How do I get this current_time variable to update when the webpage is reloaded in Flask?

from flask import Flask, render_template
app=Flask(__name__) 
import time
from datetime import datetime

from apscheduler.schedulers.background import BackgroundScheduler

current_time = 000
sched = BackgroundScheduler()
def job1():
    print('this prints 5 sec')
    now = datetime.now()
    current_time = now.strftime("%d/%m/%Y %H:%M:%S")

@app.route('/')
def home():
    return render_template('home.html', current_time=current_time)

if __name__ == '__main__':
    sched.add_job(id='job1', func=job1, trigger = 'interval', seconds=5)
    sched.start()
    app.run(host='0.0.0.0')
    app.run(debug=True, use_reloader=False)

When I run this, the 'this prints 5 seconds' part works in the terminal, but the {{current_time}} does not update on the web page when it is reloaded. Just stays "0"

(I know there are other ways to get the current time on a web page, this is just a simplified example where i want to regularly update variables then have them updated on the html page when the page is loaded.)


Solution

  • To update the current_time variable, you need to update it within the job1() / home() function. Accessing it via the global variable should work:

    def home():
         global current_time
         ...
    
    def job1():
        global current_time
        ...