473,779 Members | 2,089 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Time out question

My application makes several connections to
a remote database server via tcp/ip.
Usually all is fine,but occasionally the server is
down or the internet does not work and then there is
the 30 sec to several minutes timeout wait for the
tcp to give up.
Is there anything I can do without using
threads,sockets ,twisted etc. to have following :

pseudocode :

try for 10 seconds
if database.connec ted :
do your remote thing
except raise after 10 seconds
abort any connection attempt
do something else
Thanks
Jul 3 '06 #1
6 1678
DarkBlue <no****@nixmail .comwrote:
My application makes several connections to
a remote database server via tcp/ip.
Usually all is fine,but occasionally the server is
down or the internet does not work and then there is
the 30 sec to several minutes timeout wait for the
tcp to give up.
Is there anything I can do without using
threads,sockets ,twisted etc. to have following :

pseudocode :

try for 10 seconds
if database.connec ted :
do your remote thing
except raise after 10 seconds
abort any connection attempt
do something else
Sure, see function setdefaulttimeo ut in module socket. Just call it as
you wish before trying the DB connection and catch the resulting
exception.
Alex
Jul 3 '06 #2
>
Sure, see function setdefaulttimeo ut in module socket. Just call it as
you wish before trying the DB connection and catch the resulting
exception.
Alex
That should do it.

Thanks
Db
Jul 3 '06 #3
Alex Martelli <al***@mac.comw rote:
DarkBlue <no****@nixmail .comwrote:
try for 10 seconds
if database.connec ted :
do your remote thing
except raise after 10 seconds
abort any connection attempt
do something else

Sure, see function setdefaulttimeo ut in module socket. Just call it as
you wish before trying the DB connection and catch the resulting
exception.
It would be nice to have language support for the general case, ie a
general purpose timeout.

In python 2.5 wouldn't it be nice to write

with timeout(seconds =10) as time_exceeded:
do potentially time consuming stuff not necessarily involving sockets
if time_exceeded:
report an error or whatever

Here is some code I came up with to implement this idea for
python2.3+. It should be cross platform but I only tested it on
linux. I think there may still be a threading bug in there (see
FIXME), but it seems to work. It requires ctypes for access to
PyThreadState_S etAsyncExc).

It is mostly test code as it took absolutely ages to debug! Threading
code is hard ;-)

............... ............... ............... ............... .

"""
General purpose timeout mechanism not using alarm(), ie cross platform

Eg

from timeout import Timeout, TimeoutError

def might_infinite_ loop(arg):
while 1:
pass

try:
Timeout(10, might_infinite_ loop, "some arg")
except TimeoutError:
print "Oops took too long"
else:
print "Ran just fine"

"""

import threading
import time
import sys
import ctypes
import os

class TimeoutError(Ex ception):
"""Thrown on a timeout"""
PyThreadState_S etAsyncExc = ctypes.pythonap i.PyThreadState _SetAsyncExc
_c_TimeoutError = ctypes.py_objec t(TimeoutError)

class Timeout(threadi ng.Thread):
"""
A General purpose timeout class
timeout is int/float in seconds
action is a callable
*args, **kwargs are passed to the callable
"""
def __init__(self, timeout, action, *args, **kwargs):
threading.Threa d.__init__(self )
self.action = action
self.args = args
self.kwargs = kwargs
self.stopped = False
self.exc_value = None
self.end_lock = threading.Lock( )
# start subtask
self.setDaemon( True) # FIXME this shouldn't be needed but is, indicating sub tasks aren't ending
self.start()
# Wait for subtask to end naturally
self.join(timeo ut)
# Use end_lock to kill the thread in a non-racy
# fashion. (Using isAlive is racy). Poking exceptions into
# the Thread cleanup code isn't a good idea either
if self.end_lock.a cquire(False):
# gained end_lock =sub thread is still running
# sub thread is still running so kill it with a TimeoutError
self.exc_value = TimeoutError()
PyThreadState_S etAsyncExc(self .id, _c_TimeoutError )
# release the lock so it can progress into thread cleanup
self.end_lock.r elease()
# shouldn't block since we've killed the thread
self.join()
# re-raise any exception
if self.exc_value:
raise self.exc_value
def run(self):
self.id = threading._get_ ident()
try:
self.action(*se lf.args, **self.kwargs)
except:
self.exc_value = sys.exc_value
# only end if we can acquire the end_lock
self.end_lock.a cquire()

if __name__ == "__main__":

def _spin(t):
"""Spins for t seconds"""
start = time.time()
end = start + t
while time.time() < end:
pass

def _test_time_limi t(name, expecting_time_ out, t_limit, fn, *args, **kwargs):
"""Test Timeout"""
start = time.time()

if expecting_time_ out:
print "Test",name,"sh ould timeout"
else:
print "Test",name,"sh ouldn't timeout"

try:
Timeout(t_limit , fn, *args, **kwargs)
except TimeoutError, e:
if expecting_time_ out:
print "Timeout generated OK"
else:
raise RuntimeError("W asn't expecting TimeoutError Here")
else:
if expecting_time_ out:
raise RuntimeError("W as expecting TimeoutError Here")
else:
print "No TimeoutError generated OK"

elapsed = time.time() - start
print "That took",elapsed," seconds for timeout of",t_limit

def test():
"""Test code"""

# NB the commented out bits of code don't work with this type
# of timeout nesting.

# no nesting
_test_time_limi t("simple #1", True, 5, _spin, 10)
_test_time_limi t("simple #2", False, 10, _spin, 5)

# 1 level of nesting
_test_time_limi t("nested #1", True, 4, _test_time_limi t,
"nested #1a", True, 5, _spin, 10)
_test_time_limi t("nested #2", False, 6, _test_time_limi t,
"nested #2a", True, 5, _spin, 10)
#_test_time_lim it("nested #3", True, 4, _test_time_limi t,
# "nested #3a", False, 10, _spin, 5)
_test_time_limi t("nested #4", False, 6, _test_time_limi t,
"nested #4a", False, 10, _spin, 5)

# 2 level of nesting
_test_time_limi t("nested #5", True, 3, _test_time_limi t,
"nested #5a", True, 4, _test_time_limi t,
"nested #5b", True, 5, _spin, 10)
#_test_time_lim it("nested #6", True, 3, _test_time_limi t,
# "nested #6a", False, 6, _test_time_limi t,
# "nested #6b", True, 5, _spin, 10)
#_test_time_lim it("nested #7", True, 3, _test_time_limi t,
# "nested #7a", True, 4, _test_time_limi t,
# "nested #7b", False, 10, _spin, 5)
#_test_time_lim it("nested #8", True, 3, _test_time_limi t,
# "nested #8a", False, 6, _test_time_limi t,
# "nested #8b", False, 10, _spin, 5)
_test_time_limi t("nested #9", False, 7, _test_time_limi t,
"nested #9a", True, 4, _test_time_limi t,
"nested #9b", True, 5, _spin, 10)
_test_time_limi t("nested #10", False, 7, _test_time_limi t,
"nested #10a",False, 6, _test_time_limi t,
"nested #10b",True, 5, _spin, 10)
#_test_time_lim it("nested #11", False, 7, _test_time_limi t,
# "nested #11a",True, 4, _test_time_limi t,
# "nested #11b",False, 10, _spin, 5)
_test_time_limi t("nested #12", False, 7, _test_time_limi t,
"nested #12a",False, 6, _test_time_limi t,
"nested #12b",False, 10, _spin, 5)

print "All tests OK"

test()
--
Nick Craig-Wood <ni**@craig-wood.com-- http://www.craig-wood.com/nick
Jul 3 '06 #4
On 2006-07-03, Nick Craig-Wood <ni**@craig-wood.comwrote:
Alex Martelli <al***@mac.comw rote:
> DarkBlue <no****@nixmail .comwrote:
try for 10 seconds
if database.connec ted :
do your remote thing
except raise after 10 seconds
abort any connection attempt
do something else

Sure, see function setdefaulttimeo ut in module socket. Just call it as
you wish before trying the DB connection and catch the resulting
exception.

It would be nice to have language support for the general case, ie a
general purpose timeout.
I just use signal.alarm():

import signal,sys

def alarmHandler(si gnum, frame):
raise 'Timeout'

signal.signal(s ignal.SIGALRM, alarmHandler)

while 1:
try:
signal.alarm(5)
t = sys.stdin.readl ine()
signal.alarm(0)
print t
except 'Timeout':
print "too slow"

--
Grant Edwards grante Yow! I will SHAVE and
at buy JELL-O and bring my
visi.com MARRIAGE MANUAL!!
Jul 3 '06 #5

Grant Edwards wrote:
I just use signal.alarm():

import signal,sys

def alarmHandler(si gnum, frame):
raise 'Timeout'

signal.signal(s ignal.SIGALRM, alarmHandler)

while 1:
try:
signal.alarm(5)
t = sys.stdin.readl ine()
signal.alarm(0)
print t
except 'Timeout':
print "too slow"

--
Very nice, but UNIX only.

Jul 3 '06 #6
Grant Edwards <gr****@visi.co mwrote:
On 2006-07-03, Nick Craig-Wood <ni**@craig-wood.comwrote:
Alex Martelli <al***@mac.comw rote:
DarkBlue <no****@nixmail .comwrote:
try for 10 seconds
if database.connec ted :
do your remote thing
except raise after 10 seconds
abort any connection attempt
do something else

Sure, see function setdefaulttimeo ut in module socket. Just call it as
you wish before trying the DB connection and catch the resulting
exception.
It would be nice to have language support for the general case, ie a
general purpose timeout.

I just use signal.alarm():
There are quite a lot of problems with alarm()

1) doesn't work on windows
2) there is only one alarm so nested alarms are tricky
3) alarm() only has 1 second resolution, however you can use the POSIX
setitimer() which has better resolution
4) signals make havoc with some things (signals are basically
interrupts passed to user space under unix)
5) alarm() doesn't play nice with threads

All that said it does work under unix for a lot of programs. Here is
a module which fixes point 2) anyway...

It is a lot easier to follow than the threads example I posted
earlier. There are still potential race conditions though even with
something as simple as alarm()!

............... ............... ............... ............... .

"""
Implement time limited function calls. Only works on platforms which
support the signal module and signal.alarm()

Eg

from time_limit import time_limit, TimeOut

def might_infinite_ loop(arg):
while 1:
pass

try:
time_limit(10, might_infinite_ loop, "some arg")
except TimeOut:
print "Oops took too long"
else:
print "Ran just fine"

"""

import signal
import time
import inspect

class TimeOut(Excepti on):
"""Thrown on alarm"""
pass

class _NestedTimeOut( Exception):
"""Thrown on TimeOut detected for next layer"""
pass

def _sig_alarm(sign um, frame):
"""Alarm handler for this module"""
raise TimeOut()

def time_limit(t_li mit, fn, *args, **kwargs):
"""
Calls fn with the *args and **kwargs returning its result or
raising a TimeOut exception if it doesn't complete within t
seconds
"""

# Turn alarm off and read old value
old_t_limit = signal.alarm(0)
start_time = time.time()
# Install new handler remembering old
old_handler = signal.signal(s ignal.SIGALRM, _sig_alarm)
# Set the timer going
signal.alarm(t_ limit)

try:
try:
try:
rc = fn(*args, **kwargs)
except _NestedTimeOut:
raise TimeOut()
finally:
# Disable alarm
signal.alarm(0)
finally:
# Alarm will be disabled or will have gone off when we get here
# Restore the old handler
signal.signal(s ignal.SIGALRM, old_handler)
# If there was an alarm running restore it
if old_t_limit 0:
# Calculate how much of the old timeout is left
elapsed_time = time.time() - start_time
old_t_limit = int(round(old_t _limit - elapsed_time, 0))
if old_t_limit <= 0:
# Alarm should have gone off so call old signal handler
if old_handler == _sig_alarm:
# If handler is our handler then...
raise _NestedTimeOut( )
else:
# Call old handler
old_handler(sig nal.SIGALRM, inspect.current frame())
else:
# Re-enable alarm
signal.alarm(ol d_t_limit)

return rc

if __name__ == "__main__":

def _spin(t):
"""Spins for t seconds"""
start = time.time()
end = start + t
while time.time() < end:
pass

def _test_time_limi t(name, expecting_time_ out, t_limit, fn, *args, **kwargs):
"""Test time_limit"""
start = time.time()

if expecting_time_ out:
print "Test",name,"sh ould timeout"
else:
print "Test",name,"sh ouldn't timeout"

try:
time_limit(t_li mit, fn, *args, **kwargs)
except TimeOut, e:
if expecting_time_ out:
print "Timeout generated OK"
else:
raise RuntimeError("W asn't expecting TimeOut Here")
else:
if expecting_time_ out:
raise RuntimeError("W as expecting TimeOut Here")
else:
print "No timeout generated OK"

elapsed = time.time() - start
print "That took",elapsed," seconds for timeout of",t_limit

def test():
"""Test code"""

# no nesting
_test_time_limi t("simple #1", True, 5, _spin, 10)
_test_time_limi t("simple #2", False, 10, _spin, 5)

# 1 level of nesting
_test_time_limi t("nested #1", True, 4, _test_time_limi t, "nested #1a", True, 5, _spin, 10)
_test_time_limi t("nested #2", False, 6, _test_time_limi t, "nested #2a", True, 5, _spin, 10)
_test_time_limi t("nested #3", True, 4, _test_time_limi t, "nested #3a", False, 10, _spin, 5)
_test_time_limi t("nested #4", False, 6, _test_time_limi t, "nested #4a", False, 10, _spin, 5)

# 2 level of nesting
_test_time_limi t("nested #5", True, 3, _test_time_limi t, "nested #5a", True, 4, _test_time_limi t, "nested #5b", True, 5, _spin, 10)
_test_time_limi t("nested #6", True, 3, _test_time_limi t, "nested #6a", False, 6, _test_time_limi t, "nested #6b", True, 5, _spin, 10)
_test_time_limi t("nested #7", True, 3, _test_time_limi t, "nested #7a", True, 4, _test_time_limi t, "nested #7b", False, 10, _spin, 5)
_test_time_limi t("nested #8", True, 3, _test_time_limi t, "nested #8a", False, 6, _test_time_limi t, "nested #8b", False, 10, _spin, 5)
_test_time_limi t("nested #9", False, 7, _test_time_limi t, "nested #9a", True, 4, _test_time_limi t, "nested #9b", True, 5, _spin, 10)
_test_time_limi t("nested #10", False, 7, _test_time_limi t, "nested #10a", False, 6, _test_time_limi t, "nested #10b", True, 5, _spin, 10)
_test_time_limi t("nested #11", False, 7, _test_time_limi t, "nested #11a", True, 4, _test_time_limi t, "nested #11b", False, 10, _spin, 5)
_test_time_limi t("nested #12", False, 7, _test_time_limi t, "nested #12a", False, 6, _test_time_limi t, "nested #12b", False, 10, _spin, 5)

print "All tests OK"

test()

--
Nick Craig-Wood <ni**@craig-wood.com-- http://www.craig-wood.com/nick
Jul 4 '06 #7

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

Similar topics

7
4649
by: Valiz | last post by:
Hi, I am updating system time with IRIG time source which sends irregular pulses as shown below 11000011111100111111111111111111....(1-IRIG present and 0-IRIG not present) I need to update system time when I find a steady pulse or a series of 1's say for a span of 10-15 seconds. Is there a way to implement this in VB6? Thanks in advance. Valiz.
0
1786
by: SimonC | last post by:
I'm looking to do something similar to a feature found on Ticketmaster.com, where you select your seats at a venue, and then you have two minutes in which to take or leave them. QUESTION 1a. Inside (or just after) the same query that searches for available seats, I need to SIMULTANEOUSLY mark those seats as "on hold". I've only read about, but not yet used MySQL transactions, and wonder if this simultaneous "search-and-hold"...
2
2160
by: Steve Miller | last post by:
hello... i am a 'user' of access, meaning, i import excel files, join, and merge....that's about the extent of my expertise with ms-access. my boss wants me to create an access application that will replace our 'excel' version of time reporting. we use ms-access 2000. i have a huge book (mastering access 2000) though the cd is missing. i looked at using the wizard for time reporting, but is was designed for external clients, and the...
8
5389
by: MLH | last post by:
I have database apps that depend on accurate time settings on the system clock. Fancy that, huh? Well, am trying to sync w/ the gvt's nist time server. From a CMD window in Win XP, I type the following: C:\DB\TimNall>Gonna set time wrong - say to 8AM C:\DB\TimNall>time The current time is: 12:07:12.80 Enter the new time: 8:00:00
14
2500
by: George | last post by:
In Time.h there is a structure defined for time settings. I'm building an embedded system that has a Real Time Clock but it's not PC compatible. My question is: I don't some elements of the structure such as day of the week or day of the year, but I do know year,month,date,hour,min,sec. Does the language support filling in the missing elements. And is there a consistency check for that time structure.
1
1756
by: Rob T | last post by:
This is just a general question....trying to collect some ideas on how to approach this issue: I have a web app that has users across the country. Since they login, I can make their profiles have a time zone field, so that's no big deal. My data in question is stored in SQL 2000 in a datetime type and the server is set to Eastern time. My first question is: Is the date stored on the server stored as something like GMT format or does...
15
3652
by: Oleg Leikin | last post by:
Hi, (newbie question) I've created some simple .NET ASP application that should store cookies at the client machine. According to the documentation cookie expiration time is set via HttpCookie.Expires property, but property value is the time of day on the client. How can I possibly know client local time ?
16
2606
by: TB | last post by:
Hi all: If you think that the following comments are absolute amateurish, then please bear with me, or simply skip this thread. A couple of months back I made the decision to initiate a gradual upgrade of my web programming skills from Classic ASP / VBS to ASP.NET / VB.NET. While the study of the language differences and all the new features in .NET has so far not been a traumatic experience, I am a bit shell-schocked after
9
2194
by: FFMG | last post by:
In my site I have a config table, (MySQL), with about 30 entries; the data is loaded on every single page load. This is not the only call to the db, (we do a total of about 8 calls to the db). As with many configurations settings, once the options are set the values will not change much. So I thought it would be a good idea to move the data to a flat file. I have written a small wrapper class to first look for the file, if it exists...
6
3937
by: Geoff Cox | last post by:
Hello, at the moment I can add the combined date and time into MySQL using php $dt1 = date("Y-m-d H:i:s"); is it possible to add the date and time separately? I thought it might be
0
10139
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...
0
9931
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
7485
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
6727
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
5373
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
5504
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4037
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3632
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2869
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.