How to launch a function at regular time intervals ?
Falcolas
garrickp at gmail.com
Thu Aug 13 15:21:13 EDT 2009
On Aug 12, 3:09 pm, David <davig... at googlemail.com> wrote:
> Hi all, I'm trying to launch a function at regular time intervals but
> cannot find the way to do it. Here is the code I wrote (time_interval
> is a user defined variable in seconds):
> [snip]
> Has anyone run into a similar problem (and solved it) ?
>
> Thanks for your help
I did - as part of a script where I needed to send load into a system
at a steady rate. I ended up using threading to do the function calls,
since they were not guaranteed to complete before the next interval.
duration_start = time.time()
interval_counter = 0
while time.time() - duration_start < duration:
for thread_count in xrange(numthreads):
threading.Thread(target=exec_thread, kwargs={#snip
unimportant#}).start()
interval_counter += 1
time.sleep((duration_start + (interval * interval_counter)) -
time.time())
Executing this loop with a simple echo and time print showed that
there was no creep over time, and the deviation between intervals was
around 1/100th of a second.
I'm fairly sure I'm creating some gnarly memory leaks and such by not
joining spent threads, but it's been a non-issue in my usage. Adding a
list to keep track of the threads and join on complete threads would
be fairly trivial to implement.
I think for simpler applications, using threading.Timer to kick off
the function would work just as well.
~G
More information about the Python-list
mailing list