2014-03-16 20:59:34 -04:00
|
|
|
module Scheduler
|
|
|
|
module Deferrable
|
|
|
|
def initialize
|
|
|
|
@async = Rails.env != "test"
|
|
|
|
@queue = Queue.new
|
2014-03-17 00:22:11 -04:00
|
|
|
@mutex = Mutex.new
|
|
|
|
@thread = nil
|
|
|
|
start_thread
|
|
|
|
|
2014-03-16 20:59:34 -04:00
|
|
|
end
|
|
|
|
|
|
|
|
# for test
|
|
|
|
def async=(val)
|
|
|
|
@async = val
|
|
|
|
end
|
|
|
|
|
|
|
|
def later(&blk)
|
|
|
|
if @async
|
2014-03-17 00:22:11 -04:00
|
|
|
start_thread unless @thread.alive?
|
2014-03-16 20:59:34 -04:00
|
|
|
@queue << [RailsMultisite::ConnectionManagement.current_db, blk]
|
|
|
|
else
|
|
|
|
blk.call
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
def stop!
|
|
|
|
@thread.kill
|
|
|
|
end
|
|
|
|
|
2014-03-17 00:22:11 -04:00
|
|
|
# test only
|
|
|
|
def stopped?
|
|
|
|
!@thread.alive?
|
|
|
|
end
|
|
|
|
|
2014-03-16 20:59:34 -04:00
|
|
|
private
|
|
|
|
|
2014-03-17 00:22:11 -04:00
|
|
|
def start_thread
|
|
|
|
@mutex.synchronize do
|
|
|
|
return if @thread && @thread.alive?
|
|
|
|
@thread = Thread.new {
|
|
|
|
while true
|
|
|
|
do_work
|
|
|
|
end
|
|
|
|
}
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
2014-03-16 20:59:34 -04:00
|
|
|
def do_work
|
|
|
|
db, job = @queue.deq
|
|
|
|
RailsMultisite::ConnectionManagement.establish_connection(db: db)
|
|
|
|
job.call
|
|
|
|
rescue => ex
|
|
|
|
Discourse.handle_exception(ex)
|
|
|
|
ensure
|
|
|
|
ActiveRecord::Base.connection_handler.clear_active_connections!
|
|
|
|
end
|
|
|
|
|
|
|
|
end
|
|
|
|
|
|
|
|
class Defer
|
|
|
|
extend Deferrable
|
|
|
|
initialize
|
|
|
|
end
|
|
|
|
end
|