[英]Is there a way to run python flask function, every specific interval of time and display on the local server the output?
I am working python program using flask, where i want to extract keys from dictionary. 我正在使用flask的python程序,我想从字典中提取键。 this keys is in text format.
此键为文本格式。 But I want to repeat this above whole process after every specific interval of time.
但是我想在每个特定的时间间隔之后重复以上整个过程。 And display this output on local browser each time.
并每次在本地浏览器上显示此输出。
I have tried this using flask_apscheduler. 我已经使用flask_apscheduler进行了尝试。 The program run and shows output but only once, but dose not repeat itself after interval of time.
程序运行并显示输出,但仅显示一次,但在一段时间间隔后不会重复。
This is python program which i tried. 这是我尝试过的python程序。
@app.route('/trend', methods=['POST', 'GET'])
def run_tasks():
for i in range(0, 1):
app.apscheduler.add_job(func=getTrendingEntities, trigger='cron', args=[i], id='j'+str(i), second = 5)
return "Code run perfect"
@app.route('/loc', methods=['POST', 'GET'])
def getIntentAndSummary(self, request):
if request.method == "POST":
reqStr = request.data.decode("utf-8", "strict")
reqStrArr = reqStr.split()
reqStr = ' '.join(reqStrArr)
text_1 = []
requestBody = json.loads(reqStr)
if requestBody.get('m') is not None:
text_1.append(requestBody.get('m'))
return jsonify(text_1)
if (__name__ == "__main__"):
app.run(port = 8000)
The problem is that you're calling add_job
every time the /trend
page is requested. 问题是您每次请求
/trend
页面时都在调用add_job
。 The job should only be added once, as part of the initialization, before starting the scheduler (see below). 作为调度的一部分, 在启动调度程序之前 ,该作业仅应添加一次(请参见下文)。
It would also make more sense to use the 'interval'
trigger instead of 'cron'
, since you want your job to run every 5 seconds. 使用
'interval'
触发器而不是'cron'
也更有意义,因为您希望作业每5秒运行一次。 Here's a simple working example: 这是一个简单的工作示例:
from flask import Flask
from flask_apscheduler import APScheduler
import datetime
app = Flask(__name__)
#function executed by scheduled job
def my_job(text):
print(text, str(datetime.datetime.now()))
if (__name__ == "__main__"):
scheduler = APScheduler()
scheduler.add_job(func=my_job, args=['job run'], trigger='interval', id='job', seconds=5)
scheduler.start()
app.run(port = 8000)
Sample console output: 控制台输出样例:
job run 2019-03-30 12:49:55.339020
job run 2019-03-30 12:50:00.339467
job run 2019-03-30 12:50:05.343154
job run 2019-03-30 12:50:10.343579
You can then modify the job attributes by calling scheduler.modify_job()
. 然后,您可以通过调用
scheduler.modify_job()
来修改作业属性。
As for the second problem which is refreshing the client view every time the job runs, you can't do that directly from Flask. 至于第二个问题,那就是每次运行作业时都会刷新客户端视图,因此您不能直接从Flask中做到这一点。 An ugly but simple way would be to add
<meta http-equiv="refresh" content="1" >
to the HTML page to instruct the browser to refresh it every second. 一种丑陋但简单的方法是将
<meta http-equiv="refresh" content="1" >
到HTML页面,以指示浏览器每秒刷新一次。 A much better implementation would be to use SocketIO
to send new data in real-time to the web client. 更好的实现方法是使用
SocketIO
将新数据实时发送到Web客户端。
I would recommend that you start a demonized thread, import your application variable, then you can use with app.app_context()
in order to log into to your console. 我建议您启动一个妖魔线程,导入您的应用程序变量,然后可以
with app.app_context()
,以便登录到控制台。
It's a little bit more fiddly but allows the application to run separated by different threads. 有点麻烦,但允许应用程序由不同的线程分开运行。
I use this method to fire off a bunch of http requests concurrently. 我使用此方法同时触发一堆http请求。 The alternative is wait for each response before making a new one.
另一种方法是等待每个响应,然后再做出新响应。
I'm sure you've realised that the thread will become occupied of you run an infinitely running command. 我确定您已经意识到,运行无限运行的命令将占用线程。
Make sure to demonize the thread so that when you stop your web app it will kill the thread at the same time gracefully. 确保妖魔化线程,以便当您停止Web应用程序时,它将优雅地同时杀死线程。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.