Class: TinyWorkService

Inherits:
Object
  • Object
show all
Defined in:
lib/tiny_work_service.rb

Overview

usage:

s = TinyWorkService.new(1234)
s.stop!

Instance Method Summary collapse

Constructor Details

#initialize(port) ⇒ TinyWorkService

Returns a new instance of TinyWorkService.



7
8
9
10
11
12
13
14
15
16
17
18
19
20
# File 'lib/tiny_work_service.rb', line 7

def initialize(port)
  @service = TinyTCPService.new(port)
  @service.msg_handler = self
  @jobs = Queue.new

  @thread = Thread.new do
    loop do
      break unless @service.running?

      print "\rTinyWorkService #{@jobs.length.to_s.rjust(6)} jobs #{@service.num_clients.to_s.rjust(4)} workers\e[K"
      sleep 0.5
    end
  end
end

Instance Method Details

#<<(j) ⇒ Object

enqueue a job



43
44
45
# File 'lib/tiny_work_service.rb', line 43

def <<(j)
  @jobs << j
end

#call(m) ⇒ Object

interface for TinyTCPService

Raises:

  • (TinyTCPService::BadClient)


23
24
25
26
27
28
29
30
31
32
33
34
35
# File 'lib/tiny_work_service.rb', line 23

def call(m)
  raise TinyTCPService::BadClient.new("nil message") if m.nil?

  case
  when m[0] == '+'        # add a job to the queue
    self << m[1..]
    'ok'                  # ok, job received
  when m[0] == '-'        # take a job from the queue
    shift || ''
  else
    raise TinyTCPService::BadClient.new("Client sent invalid message: `#{m[..50]}'")
  end
end

#joinObject

join the service Thread, if you want to wait until it’s done



38
39
40
# File 'lib/tiny_work_service.rb', line 38

def join
  @thread.join
end

#shiftObject

return the first job in the work queue, if there is one present otherwise, return nil



49
50
51
52
# File 'lib/tiny_work_service.rb', line 49

def shift
  return nil if @jobs.empty?
  @jobs.shift
end

#stop!Object



54
55
56
# File 'lib/tiny_work_service.rb', line 54

def stop!
  @service.stop!
end