Wie zu töten das threading.Timer?

Habe ich ins Leben gerufen ein thread mit einem Timer Objekt. Jetzt will ich halt diesen thread, aber ich kann nicht. Ich habe verwendet cancel(), aber es funktioniert nicht. Ich weiß nicht, warum.

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)  

Den thread sollte stoppen, wenn Zähler wird gleich 20, aber es ist immer noch lebendig. Wenn ich aus der while-Schleife, es ist eine weitere Prüfung. Der Timer ist lebendig, ist der gleiche thread, ich versuche zu kündigen, aber es funktioniert nicht.

Irgendeine Idee?

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 
InformationsquelleAutor Manel López | 2016-06-01
Schreibe einen Kommentar