-
Notifications
You must be signed in to change notification settings - Fork 18
Expand file tree
/
Copy pathresque-lonely_job.rb
More file actions
64 lines (52 loc) · 1.46 KB
/
resque-lonely_job.rb
File metadata and controls
64 lines (52 loc) · 1.46 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
require 'resque-lonely_job/version'
module Resque
module Plugins
module LonelyJob
LOCK_TIMEOUT = 60 * 60 * 24 * 5 # 5 days
def lock_timeout
Time.now.to_i + LOCK_TIMEOUT + 1
end
def requeue_interval
self.instance_variable_get(:@requeue_interval) || 1
end
# Overwrite this method to uniquely identify which mutex should be used
# for a resque worker.
def redis_key(*args)
"lonely_job:#{@queue}"
end
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
def unlock_queue(*args)
Resque.redis.del(redis_key(*args))
end
def reenqueue(*args)
Resque.enqueue(self, *args)
end
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
def around_perform(*args)
begin
yield
ensure
unlock_queue(*args)
end
end
end
end
end