简体   繁体   中英

Can't stop threaded task in Python Flask

I'm looking to use Flask with Blinkstick , creating a route with a repeating task that re-occurs every 0.5 seconds, changing my Blinkstick's colour.

@app.route("/party/rave", methods=['POST'])
def flashtimer():
    threading.Timer(0.5, flashtimer).start()
    for bstick in blinkstick.find_all():
        # Inversing color
        if inverse == "true":
            bstick.set_inverse(True)
        else:
            pass
    bstick.set_random_color()
    return redirect("/")

@app.route("/kill", methods=['POST'])
def killfirst():
     # threading.Timer.Change(Timeout.Infinite, Timeout.Infinite);
    threading.Timer(0.5, flashtimer).cancel()
    return redirect("/")

My code is allowing me to stop the process, but I'm unsure how to actually kill the now threaded process when I want it to stop, as suggestions I found here to use .cancel , ._cancel and .terminate didn't work.

Any suggestions would be greatly appreciated thanks!

You are recreating a new thread and canceling it, instead of cancelling your running thread ( threading.Timer(0.5, flashtimer).cancel() ).

t = threading.Timer(0.5, invertcolor)

def invertcolor():
    for bstick in blinkstick.find_all():
        # Inversing color
        if inverse == "true":
            bstick.set_inverse(True)
        else:
            pass
    bstick.set_random_color()

@app.route("/party/rave", methods=['POST'])
def starttimer():
    t.start()
    return redirect("/")

@app.route("/kill", methods=['POST'])
def killfirst():
    t.cancel()
    return redirect("/")

I've also splited your flashtimer function in an invertcolor and a starttimer function, to stick with the single responsibility principle .

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