简体   繁体   中英

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. 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. 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.

@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. 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. 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() .

As for the second problem which is refreshing the client view every time the job runs, you can't do that directly from 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. A much better implementation would be to use SocketIO to send new data in real-time to the web client.

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.

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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM