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



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

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

.lockedObject



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

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

.pruneObject



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

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

.unlockObject



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

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

Instance Method Details

#lockObject



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

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

#locked?Boolean

Returns:

  • (Boolean)


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

def locked?
  @locked
end

#should_lock?Boolean

Returns:

  • (Boolean)


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

def should_lock?
  redis.exists(:lock)
end

#should_unlock?Boolean

Returns:

  • (Boolean)


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

def should_unlock?
  return false if should_lock?
  locked?
end

#wait_for_shutdownObject



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

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
# 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

    if not paused? and job = reserve
      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! "Sleeping for #{interval} seconds"
      procline paused? ? "Paused" : "Waiting for #{@queues.join(',')}"
      sleep interval
    end
  end

ensure
  unregister_worker
  wait_for_shutdown if locked?
end