Class: SuccessRepeater::Base

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(options = {}) ⇒ Base

Example

SuccessRepeater::Base.new(:max_seconds_run => 20.hours.to_i,

:sleep_time => 10.minutes.to_i)

Parameters:

  • options (Hash{Symbol=>Object}) (defaults to: {})


12
13
14
15
16
17
18
19
# File 'lib/success_repeater.rb', line 12

def initialize(options={})
  options = options.reverse_merge(
      :max_seconds_run => 72000, # 20 hours
      :sleep_time => 600 # 10minutes
  )
  @max_seconds_run = options[:max_seconds_run]
  @sleep_time = options[:sleep_time]
end

Instance Attribute Details

#max_seconds_runObject

Returns the value of attribute max_seconds_run.



6
7
8
# File 'lib/success_repeater.rb', line 6

def max_seconds_run
  @max_seconds_run
end

#sleep_timeObject

Returns the value of attribute sleep_time.



6
7
8
# File 'lib/success_repeater.rb', line 6

def sleep_time
  @sleep_time
end

Instance Method Details

#on_failure(e) ⇒ Object



55
56
57
58
59
60
61
# File 'lib/success_repeater.rb', line 55

def on_failure(e)
  ExceptionNotifier::Notifier.background_exception_notification(e) if defined?(ExceptionNotifier::Notifier.background_exception_notification)
  err_msg = "Succ repeater error #{e.backtrace.join("\n")}"
  Rails.logger.error(err_msg) if defined?(Rails.logger.error)
  puts err_msg
  sleep(@sleep_time)
end

#run(&block) ⇒ Object



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
# File 'lib/success_repeater.rb', line 21

def run(&block)
  done = false
  start_at = DateTime.now
  error = nil
  while !done
    begin
      if defined?(ActiveRecord::Base.transaction)
        # do it in transaction
        ActiveRecord::Base.transaction do
          block.call
        end
      else
        block.call
      end
      done = true
    rescue => e
      on_failure(e)
      # prevent blocking cron next day job
      seconds_run = ((DateTime.now - start_at) * 24 * 60 *60).to_i
      if seconds_run > @max_seconds_run
        done = true
        error = e
      else
        done = false
      end

    end
  end

  unless error.nil?
    on_failure(error)
  end
end