Created
September 3, 2014 15:29
-
-
Save stevegraham/608a33fc1b0fb0233be5 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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