简体   繁体   English

有没有一种方法可以在每个特定的时间间隔内运行python flask功能,并在本地服务器上显示输出?

[英]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.

相关问题 在每轮开始时每隔 5 分钟运行一次 function - Run a function at the start of every round 5 minute interval 在 python 中以特定的 5 分钟间隔运行作业 - Run job at specific 5 mins interval in python Python:如何在每次运行 function 时增加代码计数 - Python: How to increase count for a code every time a function is run Python Flask应用程序使用Ajax将远程服务器文本文件输出到Web服务器并在网页上显示404找不到 - Python Flask app to output remote server text file to webserver using ajax and display on webpage getting 404 not found 如何在每个间隔时间调用一个函数 Odoo 11 - How to call a function every interval time Odoo 11 每次我运行这个 python 脚本时,我都会得到输出“无”,我该如何解决这个问题? - Every time I run this python script, I get the output 'None', How do I fix this? 如何安排python脚本在特定时间每天运行? (Windows计划除外) - How can I Schedule python script to run every day at specific time ? (except Windows schedule) Scrapy-按时间间隔运行 - Scrapy - run at time interval 有没有办法在flask框架上使用python从本地目录中提取所有图像并在html图像库网页上显示图像? - Is there a way to pull all the images from a local directory using python on flask framework & display the images on a html image gallery webpage? Python烧瓶服务器需要很长时间才能启动 - Python flask server taking long time to boot
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM