How to control the time while ruby connect to oracle?

Hi,I really need your help.I have a program when I use ruby to conncet
oralcle DB.My code is(testdb.rb):

require ‘rubygems’
require ‘dbi’
puts “Begin Conn!”
dbh=DBI.connect(‘DBI:OCI8:orcl’,‘sgpm’,‘sgpm’)
puts “connect db is OK!”
dbh.disconnect

My system is solaris,usually,when i input:“ruby testdb.rb” in the
terimnate it will print connect db is OK! quickly,but sometimes when it
print “Begin Conn”,the system will wait for several minutes then have
the follow message:
env.c:257:in oci8lib.so: ORA-12170: TNS:Connect timeout occurred
(DBI::DatabaseError)
from /usr/local/lib/ruby/site_ruby/1.8/oci8.rb:229:in
initialize' from /usr/local/lib/ruby/site_ruby/1.8/DBD/OCI8/OCI8.rb:156:innew’
from /usr/local/lib/ruby/site_ruby/1.8/DBD/OCI8/OCI8.rb:156:in
connect' from /usr/local/lib/ruby/site_ruby/1.8/dbi.rb:448:inconnect’
from /usr/local/lib/ruby/site_ruby/1.8/dbi.rb:221:in `connect’
from testdb.rb:7

I have tried to use timeout() function to contorl the time,but it has no
use.
can you help me?(i want to control the code to excute in 5 secs,when it
didn’t connect to DB in 5 seconds,then it should exit.)
Thanks very much!!!

Hi,

On Sun, Jan 4, 2009 at 11:18 PM, Zane T. [email protected]
wrote:

My system is solaris,usually,when i input:“ruby testdb.rb” in the
terimnate it will print connect db is OK! quickly,but sometimes when it
print “Begin Conn”,the system will wait for several minutes then have
the follow message:
env.c:257:in oci8lib.so: ORA-12170: TNS:Connect timeout occurred
(DBI::DatabaseError)
(snip)
I have tried to use timeout() function to contorl the time,but it has no
use.

Timeout.rb doesn’t work when it is blocked in a C function.
Ruby-oci8 has non-blocking mode. But it is for established connections.
There is no way when establishing a connection as long as ruby’s thread
model is green.

can you help me?(i want to control the code to excute in 5 secs,when it
didn’t connect to DB in 5 seconds,then it should exit.)

If your platform is UNIX variant, here is a terrible workaround:
kill the process when it cannot connect to the server in 5 seconds.

testdb.rb:
require ‘rubygems’
require ‘dbi’
notify_target_pid = ARGV[0].to_i
puts “Begin Conn!”
dbh=DBI.connect(‘DBI:OCI8:orcl’,‘sgpm’,‘sgpm’)
puts “connect db is OK!”
Process.kill(“HUP”, notify_target_pid) # notify that a connection
is established.
dbh.disconnect

timeout.sh:
trap caught_signal=1 1 # trap HUP signal to set caught_signal.
ruby -Ilib -Iext/oci8 testdb.rb $$ & # when a connection is
established, HUP signal is sent.
ruby_process_pid=$!
sleep 5
if test -z “$caught_signal”; then
echo HUP signal has not been caught in 5 seconds.
echo kill the process.
kill -9 $ruby_process_pid
fi
wait $ruby_process_pid