473,785 Members | 2,266 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

how to run an arbitrary function with timeout?


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__.TookTo oLong: 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
0 1487

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

9
4964
by: Penn Markham | last post by:
Hello all, I am writing a script where I need to use the system() function to call htpasswd. I can do this just fine on the command line...works great (see attached file, test.php). When my webserver runs that part of the script (see attached file, snippet.php), though, it doesn't go through. I don't get an error message or anything...it just returns a "1" (whereas it should return a "0") as far as I can tell. I have read the PHP...
1
2743
by: deko | last post by:
I have 3 files I need to write to - and need to make sure I have a lock on each, and take action if I can't get a lock. The code below works, but I know it could be more efficient if I used a function instead of the repetitive code. Still kind of green in php.... Any help in creating a function to eliminate the repeated file lock tests is appreciated. Thanks in advance! //***** write to visdata ***** $got_it = false; $timeout = 5;
4
7702
by: Radioactive Man | last post by:
anyone know of a function like "raw_input", which collects a string from the user entry, but one where I can set a time limit, as follows: time_limit = 10 # seconds user_answer = function_xyz("GIVE ME AN ANSWER: ", time_limit) The problem with "raw_input" is that it will stop unattended script indefinitely. I'm looking for a function that does the exact same thing, but with a time limit feature, and preferably one that returns
1
1582
by: Mike | last post by:
I want to pass the address of a function to a timeout type class so that it can be used as a callback function. The function I want to use as a callback is defined like... void rf04::rc_proc(void) { } The call to the the function that uses this functions' address is like...
38
2786
by: Lasse Vågsæther Karlsen | last post by:
After working through a fair number of the challenges at www.mathschallenge.net, I noticed that some long-running functions can be helped *a lot* by caching their function results and retrieving from cache instead of calculating again. This means that often I can use a natural recursive implementation instead of unwinding the recursive calls to avoid big exponential running-times. Ok, so I thought, how about creating a decorator that...
1
2080
by: Samuel Stanojevic | last post by:
- I'm using .NET Framework 1.1. I just noticed that whenever I change the value of Session.Timeout (no matter which aspx page this happens on), at the end of the request, the 'Session_End' function gets called in my global.asax code. --More specifically, it only happens when the page is setting the value of the timeout to a value different than what it currently is.-- Yet, the session remains alive, and any variables stored in the...
12
2872
by: Chadwick Boggs | last post by:
I need to perform modulo operations on extremely large numbers. The % operator is giving me number out of range errors and the mod(x, y) function simply seems to return the wrong results. Also, my numerator is in the format of a quoted string, which the mod function can't take. Desparately searching for solutions, Chadwick. ---------------------------(end of broadcast)---------------------------
5
1454
by: Steven D'Aprano | last post by:
I have a problem and I don't know where to start looking for a solution. I have a class that needs to call an arbitrary function and wait for a result. The function, being completely arbitrary and not under my control, may be very time consuming and possibly may not even halt. My class needs to be able to give up waiting for a result after a specified amount of time. I'm thinking something conceptually like this:
2
2468
by: darknails | last post by:
Hi, I would like to know how to define a arbitrary mathematical function with one variable and a list of paramter, like, f(x). For example, in GSL library this is done as /* Definition of an arbitrary function with parameters */ struct gsl_function_struct { double (* function) (double x, void * params);
0
9489
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10162
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10100
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9959
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
7509
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6744
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5396
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5528
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
3
2893
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.