How to make Python poll a PYTHON METHOD
Nick Vatamaniuc
vatamane at gmail.com
Mon May 7 23:19:01 EDT 2007
On May 7, 10:42 pm, Nick Vatamaniuc <vatam... at gmail.com> wrote:
> On May 7, 10:07 pm, johnny <rampet... at gmail.com> wrote:
>
> > Is there a way to call a function on a specified interval(seconds,
> > milliseconds) every time, like polling user defined method?
>
> > Thanks.
>
> Sure,
>
> >>> def baz():
>
> ...: print "Baz!"
> ...:
>
> >>> from threading import Timer
> >>> timer=Timer(5.0,baz)
> >>> timer.start()
> >>> Baz!
>
> Cheers,
> -Nick Vatamaniuc
By the way, here is another way to do it. This way it will repeat, the
other one executed once. Of course, if it executed once, you can make
it do it again, but there is some trickery involved. Here is a way to
do it using threads.
Hope it helps,
-Nick Vatamaniuc
from threading import Thread
from time import sleep
class Repeater(Thread):
def __init__(self,interval,fun,*args,**kw):
Thread.__init__(self)
self.interval=interval
self.fun=fun
self.args=args
self.kw=kw
self.keep_going=True
def run(self):
while(self.keep_going):
sleep(self.interval)
self.fun(*self.args,**self.kw)
def stop_repeating(self):
self.keep_going=False
def eat(*a):
print "eating: " , ','.join([stuff for stuff in a])
r=Repeater(1.0, eat, 'eggs','spam','kelp')
r.start()
sleep(6.0)
r.stop_repeating()
More information about the Python-list
mailing list