discourse/lib/scheduler/defer.rb

87 lines
1.7 KiB
Ruby
Raw Normal View History

module Scheduler
module Deferrable
def initialize
@async = !Rails.env.test?
@queue = Queue.new
@mutex = Mutex.new
@paused = false
@thread = nil
end
def length
@queue.length
end
def pause
stop!
@paused = true
end
def resume
@paused = false
end
# for test and sidekiq
def async=(val)
@async = val
end
2017-07-27 21:20:09 -04:00
def later(desc = nil, db = RailsMultisite::ConnectionManagement.current_db, &blk)
if @async
2018-05-15 03:51:32 -04:00
start_thread unless @thread&.alive? || @paused
@queue << [db, blk, desc]
else
blk.call
end
end
def stop!
2018-05-15 03:51:32 -04:00
@thread.kill if @thread&.alive?
@thread = nil
end
# test only
def stopped?
2018-05-15 03:51:32 -04:00
!@thread&.alive?
end
def do_all_work
while !@queue.empty?
2017-07-27 21:20:09 -04:00
do_work(_non_block = true)
end
end
private
def start_thread
@mutex.synchronize do
2018-05-15 03:51:32 -04:00
return if @thread&.alive?
@thread = Thread.new { do_work while true }
end
end
# using non_block to match Ruby #deq
2017-07-27 21:20:09 -04:00
def do_work(non_block = false)
db, job, desc = @queue.deq(non_block)
db ||= RailsMultisite::ConnectionManagement::DEFAULT
2017-10-11 05:45:19 -04:00
RailsMultisite::ConnectionManagement.with_connection(db) do
begin
job.call
rescue => ex
Discourse.handle_job_exception(ex, message: "Running deferred code '#{desc}'")
end
end
rescue => ex
2017-07-27 21:20:09 -04:00
Discourse.handle_job_exception(ex, message: "Processing deferred code queue")
ensure
ActiveRecord::Base.connection_handler.clear_active_connections!
end
end
class Defer
extend Deferrable
initialize
end
end