Sha256: 4a44c2a61d624c7d27d9bd38f7a6d9e7dc027fa8f4d153ad1228df5e267ca1b3

Contents?: true

Size: 1.92 KB

Versions: 4

Compression:

Stored size: 1.92 KB

Contents

require 'belated/job_wrapper'
class Belated
  # The client class is responsible for managing the connection to the
  # DRb server. If it has no connection, it adds the jobs to a bank queue.
  # You can enqueue jobs to be processed by the server.
  # Example:
  #   client = Belated::Client.new
  #   client.enqueue(JubJub.new, at: Time.now + 5.seconds)
  class Client
    attr_accessor :queue, :bank, :banker_thread

    # Starts up the client.
    # Connects to the queue through DRb.
    # @return [void]
    def initialize
      server_uri = Belated::URI
      DRb.start_service
      self.bank = Thread::Queue.new
      self.queue = DRbObject.new_with_uri(server_uri)
    end

    # Thread in charge of handling the bank queue.
    # You probably want to memoize the client in order to avoid
    # having many threads in the sleep state.
    # @return [void]
    def start_banker_thread
      self.banker_thread = Thread.new do
        loop do
          job = bank.pop

          perform(job)
        end
      end
    end

    # The method that pushes the jobs to the queue.
    # If there is no connection, it pushes the job to the bank.
    # @param job [Object] - The the job to be pushed.
    # @param at [Date] - The time at which the job should be executed.
    # @param max_retries [Integer] - Times the job should be retried if it fails.
    # @return [JobWrapper] - The job wrapper for the queue.
    def perform(job, at: nil, max_retries: 5)
      job_wrapper = if job.is_a?(JobWrapper)
                      job
                    else
                      JobWrapper.new(job: job, at: at, max_retries: max_retries)
                    end
      pp queue.push(job_wrapper)
      job_wrapper
    rescue DRb::DRbConnError
      bank.push(job_wrapper)
      start_banker_thread if banker_thread.nil?
      banker_thread.wakeup if banker_thread.status == 'sleep'
    end
    alias perform_belated perform
    alias perform_later perform
  end
end

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
belated-0.5.3 lib/belated/client.rb
belated-0.5.2 lib/belated/client.rb
belated-0.5.1 lib/belated/client.rb
belated-0.5.0 lib/belated/client.rb