Non-polling/Non-blocking Timer? Non-polling/Non-blocking Timer? python python

Non-polling/Non-blocking Timer?


There's a built-in simple solution, using the threading module:

import threadingtimer = threading.Timer(60.0, callback)timer.start()  # after 60 seconds, 'callback' will be called## (in the meanwhile you can do other stuff...)

You can also pass args and kwargs to your callback. See here.


I think it could be really simple. Take a look at this example. It works even in a python console!

from threading import Threadfrom time import sleep# Function to be called when the timer expiresdef myFunction():    print 'Did anyone call me?'# Function with the timerdef myTimer(seconds):    sleep(seconds)    myFunction()# Thread that will sleep in background and call your function# when the timer expires.myThread = Thread(target=myTimer, args=(4,))myThread.start()

Put whatever amount of seconds you want, and keep working with the console or running the main thread/programm. You will notice that the function will be called when the timer comes to an end.

Edit

Another good example, considering the comment from @tarabyte is the one where the function is called only depending on the value of some variable or flag. I hope this would then be the answer @tarabyte is looking for.

from threading import Threadfrom time import sleepmyFlag = False# Function to be called when the flag turns ondef myFunction():    print 'Did anyone call me?'def myTimer():    global myFlag    while True:        if myFlag:            myFunction()            myFlag = False        else:            sleep(1)# Thread that will sleep in background and call your function# when the myFlag turns to be TruemyThread = Thread(target=myTimer)myThread.start()# Then, you can do whatever you want and later change the value of myFlag.# Take a look at the output inside ipython when the value of myFlag is changed.In [35]: myFlagOut[35]: FalseIn [36]: myFlag = TrueIn [37]: Did anyone call me?


Sometimes a simple solution is best, even if it polls the time. I have used this to great success before - it doesn't block if your thread doesn't stop on it.

I think I would manage this most simply by checking times, since this is so much more simple and resource economical than working out a separate threaded solution:

def event_minute_later(event):    print(time.time()) # use for testing, comment out or delete for production    return event + 60 < time.time()

And usage:

>>> event = time.time()>>> print(event)1393962502.62>>> event_minute_later(event)1393962526.73False>>> event_minute_later(event)1393962562.9True