From: Eric Hodel Date: 2006-03-29T06:02:59+09:00 Subject: Re: timeout when listening with TCPServer On Mar 28, 2006, at 12:23 PM, Bill Kelly wrote: > From: "Eric Hodel" >> >> On Mar 28, 2006, at 9:48 AM, Shea Martin wrote: >>> I want to listen for connections for 2 seconds, then timeout. Do >>> I have to use the Timeout module? >> That will be the easiest way. >> Timeout.timeout 2 do >> Thread.start server.accept do |s| new_connection s end >> end Ooh, I forgot the loop around Thread.start :( > Oh, hey, cool. Using the thread there looks like it > ought to avoid the issue with Timeout firing in the > middle of ensure blocks and circumventing them? > > I've been avoiding Timeout like "the plague" since > running into that behavior. You've timed out, so that's what's supposed to happen :) Its easy to know you've timed out though: require 'timeout' Timeout.timeout 2 do begin ensure begin sleep rescue Timeout::Error puts 'caught!' end end end But, don't nest Timeout blocks without changing the raised exception. Your code will eventually catch the wrong error and do something bad. $ ri Timeout.timeout -------------------------------------------------------- Timeout#timeout timeout(sec, exception=Error) {|if sec == nil or sec.zero?| ...} ------------------------------------------------------------------------ class MyTimeout < Timeout::Error; end Timeout.timeout 2, MyTimeout do end -- Eric Hodel - drbrain@segment7.net - http://blog.segment7.net This implementation is HODEL-HASH-9600 compliant http://trackmap.robotcoop.com