class Optimizely::AsyncScheduler

Attributes

running[R]

Public Class Methods

new(callback, interval, auto_update, logger = nil, error_handler = nil) click to toggle source
# File lib/optimizely/config_manager/async_scheduler.rb, line 22
def initialize(callback, interval, auto_update, logger = nil, error_handler = nil)
  # Sets up AsyncScheduler to execute a callback periodically.
  #
  # callback - Main function to be executed periodically.
  # interval - How many seconds to wait between executions.
  # auto_update - boolean indicates to run infinitely or only once.
  # logger - Optional Provides a logger instance.
  # error_handler - Optional Provides a handle_error method to handle exceptions.

  @callback = callback
  @interval = interval
  @auto_update = auto_update
  @running = false
  @thread = nil
  @logger = logger || NoOpLogger.new
  @error_handler = error_handler || NoOpErrorHandler.new
end

Public Instance Methods

start!() click to toggle source
# File lib/optimizely/config_manager/async_scheduler.rb, line 40
def start!
  # Starts the async scheduler.

  if @running
    @logger.log(
      Logger::WARN,
      'Scheduler is already running. Ignoring .start() call.'
    )
    return
  end

  begin
    @running = true
    @thread = Thread.new { execution_wrapper(@callback) }
  rescue StandardError => e
    @logger.log(
      Logger::ERROR,
      "Couldn't create a new thread for async scheduler. #{e.message}"
    )
    @error_handler.handle_error(e)
  end
end
stop!() click to toggle source
# File lib/optimizely/config_manager/async_scheduler.rb, line 63
def stop!
  # Stops the async scheduler.

  # If the scheduler is not running do nothing.
  return unless @running

  @running = false
  @thread.exit
end

Private Instance Methods

execution_wrapper(callback) click to toggle source
# File lib/optimizely/config_manager/async_scheduler.rb, line 75
def execution_wrapper(callback)
  # Executes the given callback periodically

  loop do
    begin
      callback.call
    rescue StandardError => e
      @logger.log(
        Logger::ERROR,
        "Something went wrong when executing passed callback. #{e.message}"
      )
      @error_handler.handle_error(e)
      stop!
    end
    break unless @auto_update

    sleep @interval
  end
end