Module: HammerCLIImport::AsyncTasksReactor::Include

Included in:
BaseCommand
Defined in:
lib/hammer_cli_import/asynctasksreactor.rb

Instance Method Summary collapse

Instance Method Details

#atr_exitObject

Has to be called before main thread ends.



92
93
94
95
96
97
98
99
100
101
# File 'lib/hammer_cli_import/asynctasksreactor.rb', line 92

def atr_exit
  info 'Waiting for async tasks to finish' unless @task_map.empty?
  @mutex.synchronize do
    @thread_finish = true
    @thread.run
  end
  @thread.join
rescue NoMethodError
  nil
end

#atr_initObject

Call from init



47
48
49
50
51
52
53
54
55
56
57
# File 'lib/hammer_cli_import/asynctasksreactor.rb', line 47

def atr_init
  # Will create thread on demand
  @thread = nil

  @mutex = Mutex.new
  @queue = Queue.new
  @task_map = {}
  @thread_finish = false
  @async_tasks_todo = 0
  @async_tasks_done = 0
end

#postpone_till(uuids, &block) ⇒ Object

Call to pospone execution of @block@ till all tasks are finished Never ever use @return@ inside provided do block.



61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
# File 'lib/hammer_cli_import/asynctasksreactor.rb', line 61

def postpone_till(uuids, &block)
  if option_no_async?
    wait_for uuids, &block
    return
  end
  if uuids.empty?
    info 'Nothing to wait for, running in main thread.'
    block.call
    return
  end
  info "Registering tasks for uuids: #{uuids.inspect}."
  uuids.sort!
  @queue.enq([uuids, block])
  start_async_task_thread
  nil
end

#wait_for(uuids, &block) ⇒ Object

Variant for case when we do not want run thing in async



79
80
81
82
83
84
85
86
87
88
89
# File 'lib/hammer_cli_import/asynctasksreactor.rb', line 79

def wait_for(uuids, &block)
  info "Waiting for uuids (non async): #{uuids.inspect}."
  n = 1
  loop do
    annotated = annotate_tasks uuids
    break if annotated.all? { |_, v| v[:finished] }
    sleep n
    n = [n + 1, 10].min
  end
  block.call
end