Skip to content

Instantly share code, notes, and snippets.

@ohookins
Last active December 13, 2015 20:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ohookins/4970680 to your computer and use it in GitHub Desktop.
Save ohookins/4970680 to your computer and use it in GitHub Desktop.
Asynchronous queries with mysql2 gem and IO.select
# Set up the three different clients to different hosts, and a starting time
client1 = Mysql2::Client.new()
client2 = Mysql2::Client.new()
client3 = Mysql2::Client.new()
start_time = Time.now()
# Run the first query
query1 = "SELECT SLEEP(5);"
puts "Running Query:\n >> #{query1}\n\n"
client1.query(query1, :async => true)
# Run the second query
query2 = "SELECT SLEEP(10);"
puts "Running Query:\n >> #{query2}\n\n"
client2.query(query2, :async => true)
# Run the third query
query3 = "SELECT SLEEP(15);"
puts "Running Query:\n >> #{query3}\n\n"
client3.query(query3, :async => true)
# Wait for results. Select on query IO sockets to rapidly determine
# when the results are ready
puts "Waiting for results..."
query_ios = [IO::open(client1.socket), IO::open(client2.socket), IO::open(client3.socket)]
orig_ios = query_ios.length
received = 0
while true
# select with a timeout of 1 second
ready = IO::select(query_ios, nil, nil, 1)
next if ready.nil? # next iteration if nothing is ready
ready_reads = ready[0] # IO::select returns [[rd],[wr],[ex]]
received += ready_reads.length
print "\rReceived #{received}/#{orig_ios} results after #{(Time.now - start_time).round} seconds" if ready.length > 0
# Remove any IOs from the list to select from, if they are ready.
query_ios -= ready_reads
break if query_ios.length == 0 # Nothing left to select from
end
puts ""
# Now all results are ready
res1 = client1.async_results
res2 = client2.async_results
res3 = client3.async_results
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment