Sha256: f29404b670a62b126c67c6c052204a0319291ebf66156c286c7228e0abc2473d

Contents?: true

Size: 1.25 KB

Versions: 1

Compression:

Stored size: 1.25 KB

Contents

module SoarThreadWorker
  class ThreadWorker
    attr_accessor :event_handler
    attr_accessor :thread

    def self.create_worker(event_handler)
      ThreadWorker.new(event_handler)
    end

    def self.error(message)
      $stderr.puts "ERROR [ThreadWorker] #{message}"
    end

    def initialize(event_handler)
      @running = false
      @stopping = false
      @event_handler = event_handler
    end

    def running?
      @running and not @thread.nil?
    end

    def start
      begin
        return if (running?)
        create_thread()
        @running = true
      rescue Exception => e
        ThreadWorker::error("Exception #{e} in start")
      end
    end

    def stop
      @stopping = true
      @thread = nil
    end

    def execute
      #Inversion of control: override this method to do the work you need.
      #Return true if after execution the thread should stop, false if it
      #should continue running
      false
    end

    private

    def run
      while not @stopping
        stop if execute
        be_nice
      end
      @running = false
    end

    def create_thread
      @thread = Thread.new do
        Thread.abort_on_exception=true
        run
      end
    end

    def be_nice
      sleep(0.1)
      Thread.pass
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
soar_thread_worker-0.1.0 lib/soar_thread_worker/thread_worker.rb