Class: Batchmaker

Inherits:
Object
  • Object
show all
Defined in:
lib/batchmaker.rb,
lib/batchmaker/railtie.rb,
lib/batchmaker/version.rb,
lib/batchmaker/null_logger.rb

Defined Under Namespace

Classes: NullLogger, Railtie

Constant Summary collapse

StoppedError =
Class.new(StandardError)
VERSION =
'1.0.0'.freeze

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(name, size, tick_period, on_error: nil, &block) ⇒ Batchmaker

Returns a new instance of Batchmaker.



6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# File 'lib/batchmaker.rb', line 6

def initialize(name, size, tick_period, on_error: nil, &block)
  @name     = name
  @size     = size
  @queue    = Queue.new
  @mutex    = Mutex.new
  @count    = 0
  @action   = block
  @on_error = on_error
  @stopping  = false

  # Main thread that process the batches
  @thread = Thread.new(&method(:run))

  # Thread that ticks on a specified frequency
  @tick = Thread.new(tick_period, &method(:tick))
  @tick.abort_on_exception = true
  @tick.priority = 1
end

Class Method Details

.loggerObject



71
72
73
# File 'lib/batchmaker.rb', line 71

def self.logger
  @logger
end

.logger=(logger) ⇒ Object



67
68
69
# File 'lib/batchmaker.rb', line 67

def self.logger=(logger)
  @logger = logger
end

Instance Method Details

#<<(item) ⇒ Object



29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
# File 'lib/batchmaker.rb', line 29

def <<(item)
  if !running?
    raise StoppedError, "failure to queue item, #{ident_str} has already stopped"
  end

  @mutex.synchronize do
    @queue << [:add, item]
    @count += 1

    if @count >= @size
      @count = 0
      @queue << [:process, :size]
    end
  end

  Thread.pass
end

#running?Boolean

Returns:

  • (Boolean)


25
26
27
# File 'lib/batchmaker.rb', line 25

def running?
  ["run", "sleep"].include?(@thread.status) && !@stopping
end

#shutdownObject



51
52
53
54
55
56
57
58
59
60
61
# File 'lib/batchmaker.rb', line 51

def shutdown
  info "shutting down"

  @mutex.synchronize do
    @stopping = true
    @queue << [:process]
    @queue << [:stop]
  end

  @tick.exit
end

#shutdown!Object



47
48
49
# File 'lib/batchmaker.rb', line 47

def shutdown!
  shutdown && wait
end

#waitObject



63
64
65
# File 'lib/batchmaker.rb', line 63

def wait
  @thread.join
end