How to set timer and clear timer in python?

I am new to python. Now I want to create a timer. When it expires, some action will be taken. But I can interrupt this timer and reset it. The pseudocode is as follows:

def timeout()
    print "time out!"
    T.cancel()  #reset timer T
    T = Timer(60, timeout)  
    T.start()

T = Timer(60, timeout)

def interrupt()
    T.cancel()  #reset timer T
    T = Timer(60, timeout)
    T.start()

if __name__=='__main__'
    T.start()
    while true
         if something is true 
             interrupt

The solution I came up with is to cancel the timer in interrupting the function, and then create a new timer. But it seems that the timer is canceled, and a new timer is created, which does not differ in high performance. Any idea?

+4
source share
1 answer

The threading.Timer () class , most likely you are looking for:

from __future__ import print_function
from time import sleep
from random import random
from threading import Timer

def timeout():
    print("Alarm!")

t = Timer(10.0, timeout)
t.start()              # After 10 seconds, "Alarm!" will be printed

sleep(5.0)
if random() < 0.5:     # But half of the time
     t.cancel()        # We might just cancel the timer
     print('Canceling')
+4
source

All Articles