简体   繁体   English

Flask 内的启动和停止线程

[英]Start and Stop thread inside Flask

I am wondering is there something special I need to do for ending a thread job in Flask?我想知道在 Flask 中结束线程作业需要做些什么特别的事情吗? Here is the sample code:这是示例代码:

from flask import (
    Flask, jsonify, render_template, request
)
import threading
import time
import random

app = Flask(__name__)

def task(thread_return):
    random_seconds=random.random()
    print(f'Start task {threading.current_thread().name} ')
    time.sleep(random_seconds*15)
    print(f'completed {threading.current_thread().name} ')
    thread_return['seconds']= random_seconds*5

thread_return = {'seconds': 0}

        
@app.route("/", methods=["GET", "POST"])
def index():
    if request.method == "GET":
        return render_template("index-ajax.html")

    val = request.json.get("c_check")
    t =threading.Thread(target=task, args=(thread_return,), daemon=True)
    if val==1:
        print("val1 is ", val)
        t.start()
    elif val==0:
        try:
            print('trying to kill thread')
            exit_event= threading.Event()
            exit_event.set()
        except Exception as e:
            print(e)
        print("val0 is ", val)
    
    
    
    return jsonify({"data": {"val": val}})
    
if __name__ == "__main__":
    app.run(host="127.0.0.1", port=5000, debug=True)

I've tried incorporating several examples I saw online that wraps the task function inside a class, but it didn't work, namely: Exit Thread Gracefully我尝试合并我在网上看到的几个示例,这些示例将任务 function 包装在 class 中,但它没有用,即: 优雅地退出线程

I like this other example, but I also couldn't get it to work with Flask: How Do You Kill a Python Thread我喜欢另一个例子,但我也无法让它与 Flask 一起工作:你如何杀死 Python 线程

Thank you for your help.谢谢您的帮助。

I was trying multiple rewrites and noticed that the following works.我正在尝试多次重写,并注意到以下工作。 Apparently, I needed to显然,我需要

  1. declare the threading.event() outside of the route function在路由 function 之外声明 threading.event()
  2. set the exit_event.set() inside the task function to end the task or prevent the task from running在任务 function 中设置 exit_event.set() 以结束任务或阻止任务运行
  3. and modify the task function to better mimic a long or indefinite running task并修改任务 function 以更好地模拟长时间或无限期运行的任务

Perhaps someone else have a more elegant pythonic solution.也许其他人有一个更优雅的 pythonic 解决方案。


from flask import (
    Flask, jsonify, render_template, request
)
import threading
import time
import random

app = Flask(__name__)
def task(thread_return):
    i=0
    while True:
        if exit_event.is_set(): 
            print(f'end {threading.current_thread().name} ')
            return
        i+=1
        random_seconds=random.random()
        print(f'Running task {threading.current_thread().name} {i} sec elapsed')
        time.sleep(1)

exit_event= threading.Event()
        
@app.route("/", methods=["GET", "POST"])
def index():
    if request.method == "GET":
        return render_template("index-ajax.html")

    val = request.json.get("c_check")
    exit_event.clear()
    t =threading.Thread(target=task, args=(thread_return,), daemon=True)
    if val==1:
        print("val1 is ", val)
        t.start()
    elif val==0:
        try:
            print('trying to end thread')
            exit_event.set()
        except Exception as e:
            print(e)
        print("val0 is ", val)
    
    return jsonify({"data": {"val": val}})
    
if __name__ == "__main__":
    app.run(host="127.0.0.1", port=5000, debug=True)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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