Class: BackgroundQueue::ServerLib::WorkerThread

Inherits:
Object
  • Object
show all
Defined in:
lib/background_queue/server_lib/worker_thread.rb

Overview

A Thread that processes the task queue

Instance Method Summary collapse

Constructor Details

#initialize(server) ⇒ WorkerThread

Returns a new instance of WorkerThread.



6
7
8
# File 'lib/background_queue/server_lib/worker_thread.rb', line 6

def initialize(server)
  @server = server
end

Instance Method Details

#build_clientObject



19
20
21
# File 'lib/background_queue/server_lib/worker_thread.rb', line 19

def build_client
  BackgroundQueue::ServerLib::WorkerClient.new(@server)
end

#call_worker(task) ⇒ Object



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
# File 'lib/background_queue/server_lib/worker_thread.rb', line 23

def call_worker(task)
  @server.change_stat(:tasks, -1)
  @server.change_stat(:running, 1)
  @server.logger.debug("calling worker for task #{task.id}")
  error_count = 0
  while @server.running?
    worker = @server.workers.get_next_worker
    if worker.nil?
      Kernel.sleep(1) unless !@server.running?
    else
      client = build_client
      result = client.send_request(worker, task, @server.config.secret)
      if result == :ok
        @server.logger.debug("called worker for task #{task.id}")
        @server.workers.finish_using_worker(worker, true)
        @server.task_queue.finish_task(task)
        @server.change_stat(:running, -1)
        @server.change_stat(:run_tasks, 1)
        return true
      else
        @server.logger.debug("failed calling worker for task #{task.id}")
        @server.workers.finish_using_worker(worker, result == :worker_error)
        @server.task_queue.add_task_to_error_list(task)
        return result != :stop
        #error_count += 1
        #if error_count > 5
        #  @server.logger.debug("error count exceeded for task #{task.id}, returning to queue")
        #  @server.task_queue.finish_task(task)
        #  @server.task_queue.add_task(task)
        #  return true
        #end
      end
    end
  end
  #if we get here the server stopped before we could do the task... put it back so it can be saved to disk...
  @server.logger.debug("returning task #{task.id} to queue because the server has stopped")
  @server.task_queue.finish_task(task)
  @server.task_queue.add_task(task)
  
  false
end

#get_next_taskObject



10
11
12
13
14
15
16
17
# File 'lib/background_queue/server_lib/worker_thread.rb', line 10

def get_next_task
  task = nil
  while @server.running? && task.nil?
    task = @server.task_queue.next_task
  end
  task = nil if task.nil? || !@server.running? #if the server isnt running, dont continue to process a task
  task
end

#runObject



65
66
67
68
69
70
# File 'lib/background_queue/server_lib/worker_thread.rb', line 65

def run
  while @server.running?
    task = get_next_task
    call_worker(task) unless task.nil?
  end
end