class ThreadWithTask

todo: review and mb use scheduler

Public Class Methods

new(sleep_time, name, delay = 0) click to toggle source
# File lib/mrpin/core/threads/thread_with_task.rb, line 5
def initialize(sleep_time, name, delay = 0)
  # in ms
  @sleep_time = sleep_time * 1000.0
  # in seconds
  @delay      = delay
  @name       = name
  @thread     = nil
end

Public Instance Methods

run(&block) click to toggle source
# File lib/mrpin/core/threads/thread_with_task.rb, line 15
def run(&block)
  logger = AppInfo.instance.logger

  @thread = Thread.new do
    sleep @delay

    logger.info "[THREAD STARTED]:\t #{@name}"

    loop do

      begin

        time_now_ms    = Time.now.to_ms
        next_tick_time = time_now_ms + @sleep_time

        block.call

        sleep_time_seconds = (next_tick_time - Time.now.to_ms) / 1000.0

        sleep_time_seconds = [sleep_time_seconds, 0.01].max

        sleep(sleep_time_seconds)

      rescue Exception => e
        AppInfo.instance.on_server_error("Error on #{@name} thread: #{e}", e)

        sleep (0.05)
      end #begin

    end #loop
  end # thread

  @thread.name = 'thread_with_task'

  nil
end
stop() click to toggle source
# File lib/mrpin/core/threads/thread_with_task.rb, line 53
def stop
  return if @thread.nil?

  @thread.stop
  @thread = nil

  nil
end