Module: Resque::Plugins::Lock

Defined in:
lib/resque/plugins/lock.rb

Overview

If you want only one instance of your job running at a time, extend it with this module.

For example:

require ‘resque/plugins/lock’

class UpdateNetworkGraph

extend Resque::Plugins::Lock

def self.perform(repo_id)
  heavy_lifting
end

end

While other UpdateNetworkGraph jobs will be placed on the queue, the Lock class will check Redis to see if any others are executing with the same arguments before beginning. If another is executing the job will be aborted.

If you want to define the key yourself you can override the ‘lock` class method in your subclass, e.g.

class UpdateNetworkGraph

extend Resque::Plugins::Lock

# Run only one at a time, regardless of repo_id.
def self.lock(repo_id)
  "network-graph"
end

def self.perform(repo_id)
  heavy_lifting
end

end

The above modification will ensure only one job of class UpdateNetworkGraph is running at a time, regardless of the repo_id. Normally a job is locked using a combination of its class name and arguments.

Instance Method Summary collapse

Instance Method Details

#around_perform_lock(*args) ⇒ Object

Where the magic happens.



57
58
59
60
61
62
63
64
65
66
67
68
# File 'lib/resque/plugins/lock.rb', line 57

def around_perform_lock(*args)
  # Abort if another job has created a lock.
  return unless Resque.redis.setnx(lock(*args), Time.now.utc)

  begin
    yield
  ensure
    # Always clear the lock when we're done, even if there is an
    # error.
    Resque.redis.del(lock(*args))
  end
end

#lock(*args) ⇒ Object

Override in your job to control the lock key. It is passed the same arguments as ‘perform`, that is, your job’s payload.



47
48
49
# File 'lib/resque/plugins/lock.rb', line 47

def lock(*args)
  "lock:#{name}-#{args.to_s}"
end

#locked?(*args) ⇒ Boolean

Convenience method, not used internally.

Returns:

  • (Boolean)


52
53
54
# File 'lib/resque/plugins/lock.rb', line 52

def locked?(*args)
  Resque.redis.exists(lock(*args))
end