如何让BackgroundScheduler在Flask路由中更新变量?

0 投票
1 回答
27 浏览
提问于 2025-04-14 15:21

我该如何让这个current_time变量在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)

当我运行这个时,终端里的“这打印了5秒”部分正常工作,但在网页上,{{current_time}}在重新加载时并没有更新,始终显示“0”。

(我知道还有其他方法可以在网页上获取当前时间,这只是一个简化的例子,我想定期更新变量,然后在页面加载时让它们在html页面上更新。)

1 个回答

0

要更新 current_time 这个变量,你需要在 job1()home() 这个函数里面进行更新。通过全局变量来访问它应该是可以的:

def home():
     global current_time
     ...

def job1():
    global current_time
    ...

撰写回答