如何在 Flask 中执行并行/后台任务

你能帮我完成并行任务吗?我这样做了几天,我还有更多想法。我想main()在后台连续运行任务以检查温度和控制输出。


当我启动 web 服务器时,函数main()只执行一个循环,并且 flaskapp()运行正常。


非常感谢。


from flask import Flask, render_template

import datetime

import time

from random import random

from random import seed

import threading

from pytz import utc

import atexit


app = Flask(__name__)

myThread = threading.Thread()

POOL_TIME = 5 #seconds


@app.route('/')

def index():

        return render_template('index.html', **templateData)


@app.route("/<deviceName>/<action>")

def action(deviceName, action):

        return render_template('index.html', **templateData)


def main():

        print('Init main task on background')

        time.sleep(1)

        

if __name__ == '__main__':

        #myThread = threading.Timer(POOL_TIME, main, ())

        #myThread.start()

        threading.Thread(target = main()).start()

        app.run(debug=True, host='0.0.0.0')

        #app.run(threaded=True)


慕容3067478
浏览 401回答 2
2回答

MMMHUHU

您的主要功能不会循环,因此只会执行一次。您需要添加一个循环,例如:def main():&nbsp; &nbsp; while 1 :&nbsp; &nbsp; &nbsp; &nbsp; print('Init main task on background')&nbsp; &nbsp; &nbsp; &nbsp; time.sleep(1)

繁花如伊

线程中带有“主”代码的选项(我没有包含您需要的所有导入 - 您的代码显然需要包含您已经拥有的代码):import threadingclass MonitorThread(threading.Thread):&nbsp; &nbsp; &nbsp;def run(self):&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; debug_log("Monitor system thread")&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; try:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;while 1: # Monitor the system forever while powered&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;print('Init main task on background')&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;# ... Add here whatever you want to do forever&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;time.sleep(1)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; except KeyboardInterrupt:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;GPIO.cleanup()MonitorThread().start()app = Flask(__name__) # Start webpage# Flask web page code@app.route("/")def index():# ... Include all of your Flask web page code generationif __name__ == "__main__":&nbsp; &nbsp; &nbsp;app.run(debug=False, host="0.0.0.0")如果这不起作用,请告诉我,因为我的应用程序非常复杂,但会永远运行并按要求提供网页,所以这只是因为我遗漏了一些东西。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python