我使用Timer
对象启动了一个线程。现在,我想停止这个线程,但我不能。我使用过cancel()
,但它不起作用。我不知道为什么。
import threading
import time
import sys as system
def Nop():
print("do nothing")
return 0
def function():
try:
while True:
print("hello world ")
time.sleep(2)
except KeyboardInterrupt:
print( "Good job!! exception catched")
t = threading.Timer(10, function)
t.start()
print(t.getName)
counter = 0
while True:
try:
time.sleep(1)
Nop()
counter = counter +1
print(counter)
if counter == 20:
print(t.getName)
t.cancel()
counter = 0
break
if t.is_alive() == False:
print("The Timer thread is dead...")
except KeyboardInterrupt:
print("End of program")
t.cancel()
system.exit(0)
except:
print("something wrong happens...")
if t.is_alive() == True:
print("timer is alive...")
print(t.getName)
t.cancel()
print("final")
system.exit(0)
当计数器等于20时,线程应该停止,但它仍然存在。当我离开while循环时,还有另一个检查。 Timer是活的,是同一个线程,我试图取消,但它不起作用。
任何想法?
do nothing
17
hello world
do nothing
18
do nothing
19
hello world do nothing
20
<bound method _Timer.getName of <_Timer(Thread-6, started daemon 9916)>>
timer is alive...
<bound method _Timer.getName of <_Timer(Thread-6, started daemon 9916)>>
final
To exit: use 'exit', 'quit', or Ctrl-D.
An exception has occurred, use %tb to see the full traceback.
SystemExit: 0
hello world
hello world
hello world
hello world
答案 0 :(得分:5)
这里的问题可以通过更仔细地阅读the documentation来解决。定时器线程的cancel
方法&#34; ...仅在定时器仍处于等待阶段时才有效。&#34;
当您调用t.cancel
时,计时器已经触发,并且其相关功能正在执行,因此它不再处于等待阶段&#34;,即使该功能实际上花费了大部分时间时间睡觉 - 这并不意味着它处于等待阶段,当计时器触发时它会终止..
更一般地说,没有积极合作就无法杀死一个帖子,因为several SO answers已经很好地总结了。
不应使用cancel
,而应设置function
查看的某种标志,以确定是否应终止其循环(以及整个线程)。
答案 1 :(得分:0)
尝试:
del threadTimer
这不是行之有效的方法,但是在等待阶段应该使用cancel
方法。请参阅文档以获取更多帮助。您正在尝试在等待阶段之后使用取消计时器。
如果del
语句不起作用,请尝试以下操作:
threadTimer = None
希望其中一些帮助。