-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathworker_server.rb
55 lines (45 loc) · 1.09 KB
/
worker_server.rb
1
2
3
4
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
49
50
51
52
53
54
55
require './queue_adapter.rb'
require 'thread'
class WorkerServer
DEFAULT_WORKERS_COUNT = 3
attr_reader :stopped
def initialize(workers_count = DEFAULT_WORKERS_COUNT)
@workers_count = workers_count
end
def start
@stopped = false
@workers = workers_count.times.map do
launch_worker_thread
end
end
def stop
@stopped = true
workers.map(&:join)
workers.clear
true
end
def log(message)
print("#{message}\n")
end
private
attr_reader :workers_count, :workers
def launch_worker_thread
Thread.new do
begin
while (job = QueueAdapter.next_job) || !stopped
(sleep(0.5) && next) unless job
execute_job(job)
end
rescue ThreadError
rescue => ex
log("ENQUEUED Job Failed: #{ex.class}: #{ex.message}")
# TODO. retry
end
end
end
def execute_job(job)
result = job.perform
log("Finished computing ENQUEUED job #{job.class_name} - Result: #{result}") if result
log("Error executing ENQUEUED job #{job.class_name} - Result: #{job.error}") unless result
end
end