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

how to run an arbitrary function with timeout?

P: n/a

i'm building a test suite on top of unittest, and some
of the tests involve things that might hang, like trying
to connect to a wedged server. so i'd like a simple function
that i can call that will run a given (func,args) pair and
return either the value or raise an exception if it times
out. this seems like it should be straightforward, but i've
not had much luck getting it to work.

my latest attempt, below, raises the exception ok,
but still doesn't return until snooze() completes:

--> xx
going to sleep
Traceback (most recent call last):
File "./xx", line 26, in ?
print RunWithTimeout( snooze, (10,), 2 )
File "./xx", line 16, in RunWithTimeout
raise TookTooLong, 'fsdfsdf'
__main__.TookTooLong: fsdfsdf

....8 second delay here...

waking up
can someone tell me what i'm doing wrong?

thanks

------------------------
#!/usr/bin/env python2.3

from threading import *
from time import sleep

class TookTooLong( Exception ):
pass

def RunWithTimeout( func, args, timeout ):
t = Thread( target=func, args=args )
t.start()
t.join( timeout )

if t.isAlive():
del t
raise TookTooLong, 'fsdfsdf'
return 'ok'
def snooze( duration ):
print 'going to sleep'
sleep( duration )
print 'waking up'

if __name__ == '__main__':
print RunWithTimeout( snooze, (10,), 2 )

----
Garry Hodgson, Technology Consultant, AT&T Labs

Be happy for this moment.
This moment is your life.

Jul 18 '05 #1
Share this question for a faster answer!
Share on Google+

This discussion thread is closed

Replies have been disabled for this discussion.