Skip to content

Instantly share code, notes, and snippets.

@schmurfy
Created November 1, 2011 14:21
Show Gist options
  • Save schmurfy/1330609 to your computer and use it in GitHub Desktop.
Save schmurfy/1330609 to your computer and use it in GitHub Desktop.
em_mysql2
gem 'activerecord', '3.1.1'
gem 'mysql2', '~> 0.3.0'
gem 'em-synchrony', '1.0.0'
require 'logger'
require 'fiber'
require 'active_record'
require 'mysql2'
require 'eventmachine'
require 'em-synchrony'
require 'em-synchrony/activerecord'
ActiveRecord::Base.logger = Logger.new($stdout)
ActiveRecord::Base.establish_connection(
:adapter => 'em_mysql2',
:database => "test",
:username => "root",
:pool => 1
)
def log(msg)
t = Time.now.strftime("%H:%M:%S")
puts("[#{t}] #{msg}")
end
def get_time
Time.now.to_f * 1000
end
def do_job
log "[#{'%x' % Fiber.current.object_id}] Waiting"
started_at = get_time()
ActiveRecord::Base.connection_pool.with_connection do |conn|
working_at = get_time()
log "[#{'%x' % Fiber.current.object_id}] Working with (#{'%x' % conn.object_id})"
ActiveRecord::Base.connection.execute("SELECT SLEEP(1)")
now = get_time()
log "[#{'%x' % Fiber.current.object_id}] Done (wait: #{(working_at - started_at).to_i}ms, execution: #{(now - working_at).to_i}ms)"
end
end
DELAY = 0
EM::run do
5.times do |n|
EM::add_timer(n * DELAY) do
Fiber.new{ do_job() }.resume
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment