Class: Resque::Worker

Inherits:
Object
  • Object
show all
Defined in:
lib/resque/plugins/heroku_scaler/worker.rb

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.lockObject



76
77
78
# File 'lib/resque/plugins/heroku_scaler/worker.rb', line 76

def self.lock
  redis.set(:lock, true)
end

.lockedObject



72
73
74
# File 'lib/resque/plugins/heroku_scaler/worker.rb', line 72

def self.locked
  Array(redis.smembers(:locked))
end

.pruneObject



85
86
87
88
89
90
# File 'lib/resque/plugins/heroku_scaler/worker.rb', line 85

def self.prune
  all_workers = Worker.all
  all_workers.each do |worker|
    worker.unregister_worker
  end
end

.unlockObject



80
81
82
83
# File 'lib/resque/plugins/heroku_scaler/worker.rb', line 80

def self.unlock
  redis.del(:lock)
  redis.del(:locked)
end

Instance Method Details

#lockObject



54
55
56
57
# File 'lib/resque/plugins/heroku_scaler/worker.rb', line 54

def lock
  redis.sadd(:locked, self)
  @locked = true
end

#locked?Boolean

Returns:

  • (Boolean)


59
60
61
# File 'lib/resque/plugins/heroku_scaler/worker.rb', line 59

def locked?
  @locked
end

#should_lock?Boolean

Returns:

  • (Boolean)


50
51
52
# File 'lib/resque/plugins/heroku_scaler/worker.rb', line 50

def should_lock?
  redis.exists(:lock)
end

#should_unlock?Boolean

Returns:

  • (Boolean)


63
64
65
66
# File 'lib/resque/plugins/heroku_scaler/worker.rb', line 63

def should_unlock?
  return false if should_lock?
  locked?
end

#wait_for_shutdownObject



68
69
70
# File 'lib/resque/plugins/heroku_scaler/worker.rb', line 68

def wait_for_shutdown
  sleep 0.1 until shutdown? or should_unlock?
end

#work(interval = 5.0, &block) ⇒ Object



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
# File 'lib/resque/plugins/heroku_scaler/worker.rb', line 5

def work(interval = 5.0, &block)
  interval = Float(interval)
  $0 = "resque: Starting"
  startup

  loop do
    break if shutdown?
    
    if should_lock?
      lock
      break
    end

    pause if should_pause?

    if job = reserve(interval)
      log "got: #{job.inspect}"
      job.worker = self
      run_hook :before_fork, job
      working_on job

      if @child = fork
        srand # Reseeding
        procline "Forked #{@child} at #{Time.now.to_i}"
        Process.wait(@child)
      else
        procline "Processing #{job.queue} since #{Time.now.to_i}"
        perform(job, &block)
        exit! unless @cant_fork
      end

      done_working
      @child = nil
    else
      break if interval.zero?
      log! "Timed out after #{interval} seconds"
      procline paused? ? "Paused" : "Waiting for #{@queues.join(',')}"
    end
  end

ensure
  unregister_worker
  wait_for_shutdown if locked?
end