Skip to content

Instantly share code, notes, and snippets.

@stevegraham
Created September 3, 2014 15:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save stevegraham/608a33fc1b0fb0233be5 to your computer and use it in GitHub Desktop.
Save stevegraham/608a33fc1b0fb0233be5 to your computer and use it in GitHub Desktop.
module PaymentGatewayCheck
@available = nil
MUTEX = Mutex.new
TASK = PeriodicTask.new(every: 5.seconds, run_immediately: !Rails.env.test?) do
begin
result = HTTParty.get ENV['PAYMENT_GATEWAY_PING_ENDPOINT']
MUTEX.synchronize { @available = result.success? }
rescue SystemCallError
MUTEX.synchronize { @available = false }
end
end
def available?
MUTEX.synchronize { !!@available }
end
%i<run stop>.each { |m| define_method(m) { TASK.send(m) } }
extend self
end
class PeriodicTask
def initialize(every:, run_immediately: true)
@mutex = Mutex.new
@stop_next_tick = false
block = proc
@thread = Thread.new do
Thread.stop unless run_immediately
while true
block.call
sleep every
Thread.stop if @mutex.synchronize { @stop_next_tick }
end
end
end
def run
@mutex.synchronize { @stop_next_tick = false }
@thread.run
end
def stop
@mutex.synchronize { @stop_next_tick = true }
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment