[英]Can't stop threaded task in Python Flask
我希望将Flask与Blinkstick结合使用,以每0.5秒重复一次的重复任务创建一条路线,以更改Blinkstick的颜色。
@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("/")
我的代码允许我停止该进程,但是我不确定如何在想要停止该线程的过程中将其终止,因为我在这里发现使用.cancel
, ._cancel
和.terminate
无效。
任何建议将不胜感激,谢谢!
您正在重新创建一个新线程并取消它,而不是取消正在运行的线程( 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("/")
我还将您的flashtimer
函数flashtimer
为invertcolor
和starttimer
函数,以遵循单一职责原则 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.