threading module timer object

Mongryong Mongryong at sympatico.ca
Tue Feb 4 14:07:25 EST 2003


On Tue, 2003-02-04 at 13:19, .d.hos wrote:
> > BTW, what you're doing is kind of 'hacky' (weird).  What is is that
> > you're try to to do?
> 
> quite possiably - I'm a python newbie trying to learn OOP :)
> 
> with your suggestion, I get the error "flagIt() argument after * must
> be a sequence"
Take a look at the Timer class and you'll see that it looks like this:

class Timer:
	def __init__ (self, interval, function, args=[], kwargs={})
		...blah..

So the code should be:
my_self = MyClass() # 
t = Timer(myInterval, MyClass.func, [my_self])

Sorry, about that.  But I'd figure you should have been able to figure
that out.  This is a great a example where having an understanding of
how 'real' compilers (ie. c/c++) treat 'class objects' helps your
understanding of Python.  

ie. class MyClass:
	....blah..
	def func(self):
		...blah...

If you take a look at the Timer class 'run' method it will call
MyClass.func like this: self.function(*self.args, **self.kwargs).

In this example, it is equivalent to: self.function(my_self) or
my_self.func().
	
> 
> basically we're doing some logging in which the worker threads collect
> data, dump to returned values to the queue, and then log that data to
> our database. Occasionally the thread hangs while waiting for a reply
> from an unresponsive source; I was hoping to catch the threads that
> hang, and insert an exception into the db.
> 
You might be better to consider using a threading concept known as
'multiple events' instead of throwing an exception for you main thread
to catch.  With multiple events, you can use two threads: (1) your
worker thread, and (2) a timeout thread (timer).  You main thread waits
on both of these events.  If the timeout thread signals an event first,
you know that your worker thread is taking too long.  If your worker
thread signals an event first than you know your worker thread
completed.  Here's a basic pseudocode:

def myTimeoutFunc(timeoutEvt):
	timeoutEvt.signal()

def mainThread():
	jobEvt = Event()
	timeoutEvt = Event()
	mulitEvt = MultiEvent([jobEvt, timeoutEvt]) 
	# note: Python does not have multi-event type

	# main thread
	worker = MyWorker(jobEvt)
	timer = Timer(interval, myTimeoutFunc, timeoutEvt)
	worker.start()
	timer.start()

	evt = multiEvt.wait()
	if evt is timeoutEvt:
		if not worker.isDone(): # double-check!!
			worker.abort()
			print "What a bad worker!!!"
	else:
		timer.cancel()
		print "What a good worker!!!"


Again, this meant to be pseudocode and is only one possible solution!  I
don't think Python has a multi-event type, so, you'll have to probably
get your hands dirty.  You might need some mutex/lock on resources (ie.
worker.isDone() needs to be thread-safe).

Hope that helps.






More information about the Python-list mailing list