Cancellable threading.Timer in Python

后端 未结 4 1471
南旧
南旧 2020-12-02 13:15

I am trying to write a method that counts down to a given time and unless a restart command is given, it will execute the task. But I don\'t think Python threading.Tim

4条回答
  •  庸人自扰
    2020-12-02 13:47

    You would call the cancel method after you start the timer:

    import time
    import threading
    
    def hello():
        print "hello, world"
        time.sleep(2)
    
    t = threading.Timer(3.0, hello)
    t.start()
    var = 'something'
    if var == 'something':
        t.cancel()
    

    You might consider using a while-loop on a Thread, instead of using a Timer.
    Here is an example appropriated from Nikolaus Gradwohl's answer to another question:

    import threading
    import time
    
    class TimerClass(threading.Thread):
        def __init__(self):
            threading.Thread.__init__(self)
            self.event = threading.Event()
            self.count = 10
    
        def run(self):
            while self.count > 0 and not self.event.is_set():
                print self.count
                self.count -= 1
                self.event.wait(1)
    
        def stop(self):
            self.event.set()
    
    tmr = TimerClass()
    tmr.start()
    
    time.sleep(3)
    
    tmr.stop()
    

提交回复
热议问题