Using ruby ​​timeout on thread calling database

I am using Ruby 1.9.2.

I have a thread that performs periodic database calls. Calls can be quite long, and sometimes (for various reasons) the connection to the database disappears. If it disappears, the stream just silently hangs there forever.

So, I want to wrap it all in a timeout to handle this. The problem is that the second time you need to call the timeout (always the second), it still just hangs. The timeout never takes effect. I know this problem existed in 1.8, but I was lucky that timeout.rb worked in version 1.9.

t = Thread.new do
  while true do
    sleep SLEEPTIME
    begin
      Timeout::timeout(TIMEOUTTIME) do
        puts "About to do DB stuff, it will hang here on the second timeout"
        db.do_db_stuff()
        process_db_stuff()
      end
    rescue Timeout::Error
      puts "Timed out"
      #handle stuff here
    end
  end
end

Any idea why this is happening and what I can do about it?

+5
1

, , . , , . :

Thread.abort_on_exception = true

, , , , . ( ) .

, ...

- Ruby . , n , Timeout .

rescue ensure. . , .

, , , , , . , .

- ? , - Ruby.

- . , . cronjob script, . , . , , , - .


, . , . , , , - :

t = Thread.new do
  loop do
    sleep INTERVAL
    begin
      # Execute database queries and process data
    rescue StandardError
      # Log error or recover from error situation before retrying
    end
  end
end

retry rescue , , , , , , .

+5

All Articles