Module: Resque::Plugins::LonelyJob

Defined in:
lib/resque-lonely_job.rb,
lib/resque-lonely_job/version.rb

Constant Summary collapse

LOCK_TIMEOUT =

5 days

60 * 60 * 24 * 5
VERSION =
"0.0.3"

Instance Method Summary collapse

Instance Method Details

#around_perform(*args) ⇒ Object



44
45
46
47
48
49
50
# File 'lib/resque-lonely_job.rb', line 44

def around_perform(*args)
  begin
    yield
  ensure
    unlock_queue(*args)
  end
end

#before_perform(*args) ⇒ Object



34
35
36
37
38
39
40
41
42
# File 'lib/resque-lonely_job.rb', line 34

def before_perform(*args)
  unless can_lock_queue?(*args)
    # 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) ⇒ Boolean

Returns:

  • (Boolean)


18
19
20
# File 'lib/resque-lonely_job.rb', line 18

def can_lock_queue?(*args)
  Resque.redis.setnx(redis_key(*args), lock_timeout)
end

#lock_timeoutObject



8
9
10
# File 'lib/resque-lonely_job.rb', line 8

def lock_timeout
  Time.now.utc + LOCK_TIMEOUT + 1
end

#redis_key(*args) ⇒ Object

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



14
15
16
# File 'lib/resque-lonely_job.rb', line 14

def redis_key(*args)
  "lonely_job:#{@queue}"
end

#reenqueue(*args) ⇒ Object

Unfortunately, there’s not a Resque interface for lpush so we have to role our own. This is based on Resque.push but we don’t need to call Resque.watch_queue as the queue should already exist if we’re unable to get the lock.



30
31
32
# File 'lib/resque-lonely_job.rb', line 30

def reenqueue(*args)
  Resque.enqueue(self, *args)
end

#unlock_queue(*args) ⇒ Object



22
23
24
# File 'lib/resque-lonely_job.rb', line 22

def unlock_queue(*args)
  Resque.redis.del(redis_key(*args))
end