module Resque::Plugins::LonelyJob

Constants

LOCK_TIMEOUT
VERSION

Public Instance Methods

around_perform(*args) { || ... } click to toggle source
# File lib/resque-lonely_job.rb, line 55
def around_perform(*args)
  begin
    yield
  ensure
    unlock_queue(*args)
  end
end
before_perform(*args) click to toggle source
# File lib/resque-lonely_job.rb, line 42
def before_perform(*args)
  unless can_lock_queue?(*args)
    # Sleep so the CPU's rest
    sleep(requeue_interval)

    # can't get the lock, so re-enqueue the task
    reenqueue(*args)

    # and don't perform
    raise Resque::Job::DontPerform
  end
end
can_lock_queue?(*args) click to toggle source
# File lib/resque-lonely_job.rb, line 22
def can_lock_queue?(*args)
  now = Time.now.to_i
  key = redis_key(*args)
  timeout = lock_timeout

  # Per http://redis.io/commands/setnx
  return true  if Resque.redis.setnx(key, timeout)
  return false if Resque.redis.get(key).to_i > now
  return true  if Resque.redis.getset(key, timeout).to_i <= now
  return false
end
lock_timeout() click to toggle source
# File lib/resque-lonely_job.rb, line 8
def lock_timeout
  Time.now.to_i + LOCK_TIMEOUT + 1
end
redis_key(*args) click to toggle source

Overwrite this method to uniquely identify which mutex should be used for a resque worker.

# File lib/resque-lonely_job.rb, line 18
def redis_key(*args)
  "lonely_job:#{@queue}"
end
reenqueue(*args) click to toggle source
# File lib/resque-lonely_job.rb, line 38
def reenqueue(*args)
  Resque.enqueue(self, *args)
end
requeue_interval() click to toggle source
# File lib/resque-lonely_job.rb, line 12
def requeue_interval
  self.instance_variable_get(:@requeue_interval) || 1
end
unlock_queue(*args) click to toggle source
# File lib/resque-lonely_job.rb, line 34
def unlock_queue(*args)
  Resque.redis.del(redis_key(*args))
end