running clock and triggering
constantly running a clock and trigger an o开发者_如何学编程ther function for every 5 seconds.
Please give me idea how to do this.
Thanks a bunch
>>> 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
You can use the scheduler from the sched module.
Just make the scheduled function reschedule itself every time it completes.
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)
精彩评论