2014-03-16 20:59:34 -04:00
|
|
|
module Scheduler
|
|
|
|
module Deferrable
|
|
|
|
def initialize
|
2014-08-18 02:42:48 -04:00
|
|
|
@async = !Rails.env.test?
|
2014-03-16 20:59:34 -04:00
|
|
|
@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
|
|
|
|
|
2015-02-05 00:08:52 -05:00
|
|
|
def later(desc = nil, db=RailsMultisite::ConnectionManagement.current_db, &blk)
|
2014-03-16 20:59:34 -04:00
|
|
|
if @async
|
2014-03-17 00:22:11 -04:00
|
|
|
start_thread unless @thread.alive?
|
2015-02-05 00:08:52 -05:00
|
|
|
@queue << [db, blk, desc]
|
2014-03-16 20:59:34 -04:00
|
|
|
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
|
2014-07-17 16:22:46 -04:00
|
|
|
db, job, desc = @queue.deq
|
|
|
|
begin
|
2015-02-05 00:08:52 -05:00
|
|
|
RailsMultisite::ConnectionManagement.establish_connection(db: db) if db
|
2014-07-17 16:22:46 -04:00
|
|
|
job.call
|
|
|
|
rescue => ex
|
2014-07-17 18:19:58 -04:00
|
|
|
Discourse.handle_exception(ex, {message: "Running deferred code '#{desc}'"})
|
2014-07-17 16:22:46 -04:00
|
|
|
end
|
2014-03-16 20:59:34 -04:00
|
|
|
rescue => ex
|
2014-07-17 18:19:58 -04:00
|
|
|
Discourse.handle_exception(ex, {message: "Processing deferred code queue"})
|
2014-03-16 20:59:34 -04:00
|
|
|
ensure
|
|
|
|
ActiveRecord::Base.connection_handler.clear_active_connections!
|
|
|
|
end
|
|
|
|
|
|
|
|
end
|
|
|
|
|
|
|
|
class Defer
|
|
|
|
extend Deferrable
|
|
|
|
initialize
|
|
|
|
end
|
|
|
|
end
|