Making a timebomb

Peter Hansen peter at engcorp.com
Fri Aug 5 13:00:04 EDT 2005


callmebill at gmail.com wrote:
> I have a server that right now runs infinitely.  I'd like to make it
> die after some amount of time.  I was thinking of having a timebomb
> thread that starts when the server starts.  The timebomb sits, and
> sleeps for the specified timeout period (e.g., 5 hours), then does
> something to make the main thread terminate.  But I'm too inexperienced
> to figure out what that thing is.
> 
> Any suggestions?
...
> class MyServer:
>    def __init__(self):
>        serve()

The right answer depends entirely on things you don't mention, most 
specifically just what serve() is doing in the above code.

Generally speaking, long-running code is either running in a loop, 
repeating some operations -- and a polling technique (to check for 
timeout) can be used -- or it is asynchronous, such as a server 
listening on sockets -- in which case you need either to use whatever 
builtin support is in the framework you're building on (and you should 
be building on a framework, not doing this from scratch), or you need to 
use non-blocking sockets and select(), or in the worst case you need to 
have your server connect internally to itself (think "loopback") and 
send itself a message so that the blocked threads will wake up and can 
then voluntarily terminate.

Not the clearest message I've written lately... sorry, but if that's not 
enough to point you in the right direction, give more detail and you'll 
get a better answer.

-Peter



More information about the Python-list mailing list