call a function every n mseconds

Josiah Carlson jcarlson at nospam.uci.edu
Sun Feb 22 02:47:59 CET 2004


> How can I call a function every time a specified number of milliseconds
> elapses? Javascript has setInterval() function and I need something like
> that. Currently I use this:
> def function():
> 	[...]
> 	t = threading.Timer(n, function)
> 	t.start()
> function()

I guess it all depends on what you are doing.  If you didn't need to do 
anything else, and didn't want to deal with threads:

###beginning of code
import time

def runevery(msecs, function, args=(,), kwargs={}):
     while 1:
         function(*args, **kwargs)
         time.sleep(msecs/1000.0)
###end of code

If you have other things to do:

###beginning of code
import time

timer = [time.time()]
def runevery(msecs, function, args=(,), kwargs={}):
     global timer
     if time.time() >= timer[0]:
         timer[0] += msecs/1000.0
         function(*args, **kwargs)

#call runfunct in some sort of mainloop like so:

while 1:
     asyncore.poll(1) #or something like that
     runevery(delay, function, args, kwargs)
###end of code

I hope this helps,
  - Josiah



More information about the Python-list mailing list