How to make Python poll a PYTHON METHOD

johnny rampeters at gmail.com
Thu May 10 10:14:44 EDT 2007


Is it possible to call threads inside another thread (nested threads)?

The example above creates a thread to call a function "eat" every time
based on a specified interval.
Now for example, if I make the called function "eat" to spawn threads
to do the work in a queue and when all jobs are done, spawned threads
join.  When the next interval is up this process repeat itself.

Thanks.

On May 7, 11:19 pm, Nick Vatamaniuc <vatam... at gmail.com> wrote:
> 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