Class: Jober::ThreadedManager

Inherits:
Object
  • Object
show all
Includes:
Exception, Logger
Defined in:
lib/jober/threaded_manager.rb

Instance Method Summary collapse

Methods included from Exception

#catch, #exception

Methods included from Logger

#logger, #logger=, #logger_tag

Constructor Details

#initialize(klasses = nil, opts = {}) ⇒ ThreadedManager

Returns a new instance of ThreadedManager.



13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
# File 'lib/jober/threaded_manager.rb', line 13

def initialize(klasses = nil, opts = {})
  @klasses = Array(klasses || Jober.auto_classes)
  @stopped = false
  h = Hash.new(0)
  @objects = @klasses.map do |klass|
    if klass.is_a?(String)
      klass_str = klass
      klass = Jober.find_class(klass_str)
      raise "unknown class #{klass_str}" unless klass
    end
    obj = klass.new(opts.merge(:unique_id => h[klass]))
    h[klass] += 1
    obj
  end
end

Instance Method Details

#default_sleepObject



9
10
11
# File 'lib/jober/threaded_manager.rb', line 9

def default_sleep
  @default_sleep ||= 10
end

#default_sleep=(ds) ⇒ Object



5
6
7
# File 'lib/jober/threaded_manager.rb', line 5

def default_sleep=(ds)
  @default_sleep = ds
end

#run_loopObject



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
65
66
# File 'lib/jober/threaded_manager.rb', line 35

def run_loop
  info { "run loop for #{@klasses.inspect}, in threads: #{@objects.length}" }
  @threads = @objects.map { |obj| make_thread(obj) }

  # set signals
  trap("INT") { @stopped = true }
  trap("QUIT") { @stopped = true }

  # sleeping infinitely
  sleeping

  info { "prepare quit ..." }

  # send stop to all objects
  @objects.each(&:stop!)

  # sleep a little
  sleep(0.2)

  # sleep a little to give time for threads to quit
  wait_for_kill(default_sleep.to_f)

  names = not_finished_objects_names
  if names.empty?
    info { "quit!" }
  else
    info { "quit! and force killing #{names.inspect}" }
  end

  # kill all threads, if they still alive
  @threads.select(&:alive?).each(&:kill)
end

#set_objects(objects) ⇒ Object



29
30
31
32
33
# File 'lib/jober/threaded_manager.rb', line 29

def set_objects(objects)
  c = 0
  objects.each { |o| o.instance_variable_set(:@unique_id, c); c += 1 }
  @objects = objects
end

#stop!Object



68
69
70
# File 'lib/jober/threaded_manager.rb', line 68

def stop!
  @stopped = true
end