This is really weird to me. Have been frustrated for hours. Once a RUN request received, RUNNER will start out a background thread running forever. At anytime, there will be only one running thread (i use mutex). The problem is, for status request, sometimes it returns true, sometimes it returns false.
(done method never been called, since the backend thread will run forever, so there is no way is_running? could be false)
#config/initializers/some_init.rb
RUNNER = Runner.instance
#app/controllers/some_controller.rb
class SomeController < ApplicationController
def run
RUNNER.run {
loop do
Rails.logger.debug "backend thread running #{Time.zone.now}"
sleep(5)
end
}
end
def status
Rails.logger.debug RUNNER.inspect
RUNNER.is_running?
end
end
#lib/runner.rb
require 'singleton'
class Runner
include Singleton
def initialize
@running = false
@mutex = Mutex.new
end
def run(&blk)
@mutex.synchronize do
return if @running #only one job run is allowed at anytime
@running = true
@thr = Thread.new(self) do |r|
blk.call
r.done
end
end
end
def is_running?
@mutex.synchronize{ @running }
end
private
def done
@mutex.synchronize {@running = false}
end
end