By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
444,002 Members | 1,171 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 444,002 IT Pros & Developers. It's quick & easy.

Re: Continuous Timer

P: n/a
En Fri, 30 May 2008 22:50:13 -0300, Robert Dailey <rc******@gmail.com>
escribió:
Reading through the Python 2.5 docs, I'm seeing a Timer class in the
threading module, however I cannot find a timer object that will
continuously call a function of my choice every XXXX amount of
milliseconds.
For example, every 1000 milliseconds I want a function named Foo to be
called. This would continue to happen until I terminate the timer in my
main
thread. Thanks for the help.
Use an Event object; its wait() will provide the sleep time, and when it
is set() the thread knows it has to exit.

import threading
import time

def repeat(event, every, action):
while True:
event.wait(every)
if event.isSet():
break
action()

def foo():
print "I'm bored to death..."

print "creating event and thread"
ev = threading.Event()
t1 = threading.Thread(target=repeat, args=(ev, 1.0, foo))
print "starting thread"
t1.start()
print "waiting for 10 seconds in main thread"
time.sleep(10)
print "setting event"
ev.set()
print "waiting for thread to finish"
t1.join()
print "quit"

--
Gabriel Genellina

Jun 27 '08 #1
Share this Question
Share on Google+
1 Reply


P: n/a
Gabriel Genellina wrote:
En Fri, 30 May 2008 22:50:13 -0300, Robert Dailey <rc******@gmail.com>
escribió:
>Reading through the Python 2.5 docs, I'm seeing a Timer class in the
threading module, however I cannot find a timer object that will
continuously call a function of my choice every XXXX amount of
milliseconds.
For example, every 1000 milliseconds I want a function named Foo to be
called. This would continue to happen until I terminate the timer in
my main
thread. Thanks for the help.

Use an Event object; its wait() will provide the sleep time, and when it
is set() the thread knows it has to exit.

import threading
import time

def repeat(event, every, action):
while True:
event.wait(every)
if event.isSet():
break
action()
Actually, to do this right, it's necessary to account for the time used by
"action". The code above will run no sooner than the time "every" after
the COMPLETION of action.

I've done this sort of thing under QNX, the real-time operating system,
which has better timing primitives, and seen the action executed within
a few microseconds of the correct time, every time. But that was in C++.

If you're trying to do hard real time in Python on Linux or Windows,
don't expect reliable timing. Remember, Python isn't really preemptive,
because of the global interpreter lock and the lack of thread priorities.

John Nagle
Jun 27 '08 #2

This discussion thread is closed

Replies have been disabled for this discussion.