Class: Workaholic
- Inherits:
-
Object
- Object
- Workaholic
- Defined in:
- lib/workaholic.rb,
lib/workaholic/job.rb,
lib/workaholic/worker.rb
Defined Under Namespace
Classes: Job, RunningError
Instance Attribute Summary collapse
-
#queue ⇒ Object
readonly
Returns the value of attribute queue.
-
#running ⇒ Object
readonly
Returns the value of attribute running.
-
#state ⇒ Object
readonly
Returns the value of attribute state.
Instance Method Summary collapse
-
#initialize ⇒ Workaholic
constructor
A new instance of Workaholic.
- #push(job) ⇒ Object
- #run(job) ⇒ Object
- #running? ⇒ Boolean
- #start(thread_count = 2) ⇒ Object
- #stop ⇒ Object
Constructor Details
#initialize ⇒ Workaholic
Returns a new instance of Workaholic.
9 10 11 12 13 14 |
# File 'lib/workaholic/worker.rb', line 9 def initialize @queue = Queue.new @state = :stopped @threads ||= [] @running = 0 end |
Instance Attribute Details
#queue ⇒ Object (readonly)
Returns the value of attribute queue.
5 6 7 |
# File 'lib/workaholic/worker.rb', line 5 def queue @queue end |
#running ⇒ Object (readonly)
Returns the value of attribute running.
7 8 9 |
# File 'lib/workaholic/worker.rb', line 7 def running @running end |
#state ⇒ Object (readonly)
Returns the value of attribute state.
6 7 8 |
# File 'lib/workaholic/worker.rb', line 6 def state @state end |
Instance Method Details
#push(job) ⇒ Object
69 70 71 |
# File 'lib/workaholic/worker.rb', line 69 def push( job ) @queue.push job end |
#run(job) ⇒ Object
60 61 62 63 64 65 66 67 |
# File 'lib/workaholic/worker.rb', line 60 def run( job ) begin job.run rescue puts $! puts caller.join("\n") end end |
#running? ⇒ Boolean
47 48 49 |
# File 'lib/workaholic/worker.rb', line 47 def running? @queue.size > 0 || @running > 0 end |
#start(thread_count = 2) ⇒ Object
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 |
# File 'lib/workaholic/worker.rb', line 16 def start( thread_count = 2 ) raise RunningError unless state == :stopped @state = :running thread_count.times do |i| t = Thread.start do while [:running, :stopping].include? @state begin @running += 1 run @queue.pop( true ) rescue ThreadError # when queue is empty rescue puts $! puts caller.join("\n") ensure @running -= 1 end sleep 0.016 break if @state == :stopping end end @threads.push t end if block_given? yield self sleep 0.1 while queue.size > 0 stop end end |
#stop ⇒ Object
51 52 53 54 55 56 57 58 |
# File 'lib/workaholic/worker.rb', line 51 def stop @state = :stopping while !@threads.select{ |t| t.alive? }.empty? sleep 1 end @state = :stopped @threads = [] end |