tags:

views:

58

answers:

3

Hi,

constantly running a clock and trigger an other function for every 5 seconds.

Please give me idea how to do this.

Thanks a bunch

+1  A: 
import time

while True:
    time.sleep(5)
    someFunction()

As gnibbler says, the interval will actually be (5 seconds + the time it takes to run someFunction). If you need it to be exactly 5 seconds:

targetTime = time.time()
while True:
    someFunction()
    targetTime += 5
    sleepTime = targetTime - time.time()
    if sleepTime>0:
        time.sleep(sleepTime)
interjay
This will trigger every (5 seconds + the time it takes to run `someFunction`)
gnibbler
You're right, added a more exact version
interjay
ok +1 then (extra crap to make up 15 chars grr.)
gnibbler
Turns out that sleep may -- depending on Unix signals -- not sleep the full time. So it can be even more complex if you want real accuracy.
S.Lott
+1  A: 

You can use the scheduler from the sched module.

Just make the scheduled function reschedule itself every time it completes.

Mark Byers
+3  A: 
>>> import sched, time
>>> s = sched.scheduler(time.time, time.sleep)
>>> def print_time():
...     s.enter(5, 1, print_time, ())
...     print "From print_time", time.time()
... 
>>> s.enter(0, 1, print_time, ())
Event(time=1265846894.4069381, priority=1, action=<function print_time at 0xb7d1ab1c>, argument=())
>>> s.run()
From print_time 1265846894.41
From print_time 1265846899.41
From print_time 1265846904.42
From print_time 1265846909.42
gnibbler