Sha256: fe4a6dc80d228646aceb454d10d9aea9b4ce8684946c0679d5773c3e5141947a

Contents?: true

Size: 1.02 KB

Versions: 25

Compression:

Stored size: 1.02 KB

Contents

require "thread"

module Sequel

  class Worker < Thread
      
    attr_reader :queue
    attr_reader :errors
  
    def initialize(db = nil)
      @queue = Queue.new
      @errors = []
      t = self
      t.abort_on_exception = true
      @transaction = !db.nil?
      db ? super {db.transaction {t.work}} : super {t.work}
    end
    
    def work
      loop {next_job}
    rescue Sequel::Error::WorkerStop # signals the worker thread to stop
    ensure
      rollback! if @transaction && !@errors.empty?
    end
    
    def busy?
      @cur || !@queue.empty?
    end
  
    def async(proc = nil, &block)
      @queue << (proc || block)
      self
    end
    alias_method :add, :async
    alias_method :<<, :async
  
    def join
      while busy?
        sleep 0.1
      end
      self.raise Error::WorkerStop
      super
    end

    private
    def next_job
      @cur = @queue.pop
      @cur.call
    rescue Error::WorkerStop => e
      raise e
    rescue Exception => e
      @errors << e
    ensure
      @cur = nil
    end
  end

end

Version data entries

25 entries across 25 versions & 2 rubygems

Version Path
sequel-0.4.4.2 lib/sequel/worker.rb
sequel-0.4.5 lib/sequel/worker.rb
sequel-0.5.0.2 lib/sequel/worker.rb
sequel-0.5.0.1 lib/sequel/worker.rb
sequel-0.5 lib/sequel/worker.rb
sequel_core-1.0.0.1 lib/sequel_core/worker.rb
sequel_core-1.0.10 lib/sequel_core/worker.rb
sequel_core-1.0.2 lib/sequel_core/worker.rb
sequel_core-1.0.1 lib/sequel_core/worker.rb
sequel_core-1.0.3 lib/sequel_core/worker.rb
sequel_core-1.0.4 lib/sequel_core/worker.rb
sequel_core-1.0.8.1 lib/sequel_core/worker.rb
sequel_core-1.0.6 lib/sequel_core/worker.rb
sequel_core-1.0.4.1 lib/sequel_core/worker.rb
sequel_core-1.0.7 lib/sequel_core/worker.rb
sequel_core-1.0.5 lib/sequel_core/worker.rb
sequel_core-1.0.8.2 lib/sequel_core/worker.rb
sequel_core-1.0.9.1 lib/sequel_core/worker.rb
sequel_core-1.0.8 lib/sequel_core/worker.rb
sequel_core-1.0 lib/sequel_core/worker.rb