Class: MetOnTheMiddle::Worker
- Inherits:
-
Object
- Object
- MetOnTheMiddle::Worker
- Defined in:
- lib/met_on_the_middle/worker.rb
Instance Attribute Summary collapse
-
#timer ⇒ Object
readonly
Returns the value of attribute timer.
Instance Method Summary collapse
-
#initialize(options = {}) ⇒ Worker
constructor
available options: * timer - type of timer to use, valid options are :sleep (default), :eventmachine, or :synchrony * sync - try to synchronize timer executions to whole minutes or subdivisions thereof.
-
#run_periodically(period, &block) ⇒ Object
run the given block every <period> seconds, looping infinitely unless @interrupt becomes true.
-
#start_time(period) ⇒ Object
Give some structure to worker start times so when possible they will be in sync.
-
#stop! ⇒ Object
stop worker loop at the beginning of the next round of execution.
Constructor Details
#initialize(options = {}) ⇒ Worker
available options:
* timer - type of timer to use, valid options are
:sleep (default), :eventmachine, or :synchrony
* sync - try to synchronize timer executions to whole
minutes or subdivisions thereof
10 11 12 13 14 |
# File 'lib/met_on_the_middle/worker.rb', line 10 def initialize(={}) @interrupt = false @timer = ([:timer] || :sleep).to_sym @sync = [:sync] || false end |
Instance Attribute Details
#timer ⇒ Object (readonly)
Returns the value of attribute timer.
3 4 5 |
# File 'lib/met_on_the_middle/worker.rb', line 3 def timer @timer end |
Instance Method Details
#run_periodically(period, &block) ⇒ Object
run the given block every <period> seconds, looping infinitely unless @interrupt becomes true.
19 20 21 22 23 24 25 26 27 |
# File 'lib/met_on_the_middle/worker.rb', line 19 def run_periodically(period, &block) @proc = block # store if [:eventmachine, :synchrony].include?(timer) compensated_repeat(period) # threading is already handled else @thread = Thread.new {compensated_repeat(period)} end end |
#start_time(period) ⇒ Object
Give some structure to worker start times so when possible they will be in sync.
32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 |
# File 'lib/met_on_the_middle/worker.rb', line 32 def start_time(period) if @sync earliest = Time.now + period # already on a whole minute return earliest if earliest.sec == 0 if period > 30 # bump to whole minute earliest + (60-earliest.sec) else # ensure sync to whole minute if minute is evenly divisible earliest + (period-(earliest.sec%period)) end else if period > 30 # ensure some wobble in start times, # trade a slightly irregular first period for a more even # distribution for network requests between processes start = Time.now start + (60-start.sec) + rand(60) else Time.now + period end end end |
#stop! ⇒ Object
stop worker loop at the beginning of the next round of execution
59 60 61 |
# File 'lib/met_on_the_middle/worker.rb', line 59 def stop! @interrupt = true end |