Class: Unleash::ScheduledExecutor

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(name, interval, max_exceptions = 5) ⇒ ScheduledExecutor

Returns a new instance of ScheduledExecutor.



6
7
8
9
10
11
12
# File 'lib/unleash/scheduled_executor.rb', line 6

def initialize(name, interval, max_exceptions = 5)
  self.name = name || ''
  self.interval = interval
  self.max_exceptions = max_exceptions
  self.retry_count = 0
  self.thread = nil
end

Instance Attribute Details

#intervalObject

Returns the value of attribute interval.



4
5
6
# File 'lib/unleash/scheduled_executor.rb', line 4

def interval
  @interval
end

#max_exceptionsObject

Returns the value of attribute max_exceptions.



4
5
6
# File 'lib/unleash/scheduled_executor.rb', line 4

def max_exceptions
  @max_exceptions
end

#nameObject

Returns the value of attribute name.



4
5
6
# File 'lib/unleash/scheduled_executor.rb', line 4

def name
  @name
end

#retry_countObject

Returns the value of attribute retry_count.



4
5
6
# File 'lib/unleash/scheduled_executor.rb', line 4

def retry_count
  @retry_count
end

#threadObject

Returns the value of attribute thread.



4
5
6
# File 'lib/unleash/scheduled_executor.rb', line 4

def thread
  @thread
end

Instance Method Details

#exitObject



45
46
47
48
49
50
51
# File 'lib/unleash/scheduled_executor.rb', line 45

def exit
  if self.running?
    Unleash.logger.warn "thread #{name} will exit!"
    self.thread.exit
    self.thread.join if self.running?
  end
end

#run(&blk) ⇒ Object



14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# File 'lib/unleash/scheduled_executor.rb', line 14

def run(&blk)
  self.thread = Thread.new do
    Thread.current[:name] = self.name

    loop do
      Unleash.logger.debug "thread #{name} sleeping for #{interval} seconds"
      sleep interval

      Unleash.logger.debug "thread #{name} started"
      begin
        yield
        self.retry_count = 0
      rescue Exception => e
        self.retry_count += 1
        Unleash.logger.error "thread #{name} threw exception #{e.class}:'#{e}' (#{self.retry_count}/#{self.max_exceptions})"
        Unleash.logger.error "stacktrace: #{e.backtrace}"
      end

      if self.retry_count > self.max_exceptions
        Unleash.logger.error "thread #{name} retry_count (#{self.retry_count}) exceeded max_exceptions (#{self.max_exceptions}). Stopping with retries."
        break
      end
    end
    Unleash.logger.warn "thread #{name} loop ended"
  end
end

#running?Boolean

Returns:

  • (Boolean)


41
42
43
# File 'lib/unleash/scheduled_executor.rb', line 41

def running?
  self.thread.is_a?(Thread) && self.thread.alive?
end