I've been trying to implement a MySQL connection timeout using the Time::Hires module, as the one within the DBI module only has a granularity of seconds.
This is to connect to a remote MySQL database on a VPN, as we've seen that the connection times can run as high as 3 seconds ... so we're trying to understand if there's any benefit from giving up after 200ms and trying a fresh attempt.
I've got the guts of the script worked out, to timeout after n milliseconds, and retry up to n times ... I'm just a bit worried about resources getting gobbled up, forgotten about etc etc. Basically it's my first experience with signals in general, and they scare the hell out of me.
Can someone review my code snippet, and tell me your thoughts ...
use Time::HiRes qw ( gettimeofday tv_interval setitimer ITIMER_REAL );
use DBI;
$ConnectTimeOut = 0.2; # 200 milliseconds ...
$ConnectRetrys = 5;
$ConnectAttempts = 0;
$Handle = "";
while (($ConnectAttempts < $ConnectRetrys) && ($Handle eq "")) {
eval {
local $SIG{ALRM} = sub { die "DB CONN FAIL" };
setitimer(ITIMER_REAL, $ConnectTimeOut);
$Handle = DBI->connect( "DBI:mysql:mydatabase;host=111.111.111
+.111;port=3306","myusername","mypassword",{ RaiseError => 1});
setitimer(ITIMER_REAL, 0);
};
if ($@ and $@ =~ /DB CONN FAIL/) {
print "CONNECT TIMED OUT\n";
$ConnectAttempts++;
}
if ($@ and $@ !~ /DB CONN FAIL/) {
print "SOME OTHER CONNECTION PROBLEM\n";
$ConnectAttempts++;
}
if (!$@) {
print "CONNECT IS GOOD\n";
}
}
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.