Skip to content

Instantly share code, notes, and snippets.

@Geesu
Last active August 29, 2015 14:09
Show Gist options
  • Save Geesu/defe63d00fbf4c880e84 to your computer and use it in GitHub Desktop.
Save Geesu/defe63d00fbf4c880e84 to your computer and use it in GitHub Desktop.
class Semaphore
def self.get(name, options = {})
# Create a new Redis connection specifically for the semaphore.
# Treat a semaphore as stale if it's too old. We have to assume that processing was interrupted, so that we can try the same files again.
Redis::Semaphore.new(name.to_sym,
:redis => Aperture.redis,
stale_client_timeout: options[:stale_client_timeout].try(:to_i) || 1.hour,
)
end
end
# Run this on server 1 in rails console
sema = Semaphore.get("my_semaphore_key")
sema.lock # Or you can do sema.lock do sleep(20) end
# Then run this on server 2 in rails console
sema = Semaphore.get("my_semaphore_key")
[2] pry(main)> sema.locked?
=> false
# It will always be false, even though it should return saying it is locked
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment