Frage

I'm building a task runner where each task is built from a number of commands:

def run

  begin
    #Validating task params
    set_progress "Validating params", "Validating params: #{@params}"
    validate_params

    @task_info["steps"].each do |step|
      @log.info "Running command: #{step["description"]}"

      set_progress step["description"] 

      command = Command.factory @params, step, @signature, @log
      timeout = General.in_seconds step["timeout"]

      command_res = Timeout.timeout(timeout) do
        command.execute
      end
    end 

    set_progress "Completed"
  rescue Exception => exception
    @log.error exception.message + "\nBACK TRACE:\n" + exception.backtrace.join("\n")
    set_progress @progress, "Failed, check logs. exception: #{exception.message}"
  end 

end

Now the command is ran by "command.execute", and there is a field inside the command class which is called "current_status" which i would like to monitor each X seconds and check the command status in order to update the user about the command status, how can i do it ? i probably need to run the command in a separate thread and then monitor it, but how can i monitor it ?

War es hilfreich?

Lösung

a quick and dirty methodology which might contain syntax errors :P

class JobManager
  def initialize
    @threads =[]
  end

  def registered_jobs
    @registered_jobs ||= [Job1.new, Job2.new]
  end

  def start_jobs
    registered_jobs.each {|j| @threads << Thread.new { j.run } }  
  end

  def statuses?
    registered_jobs.collect {|j| j.status? }
  end
end

Usage:

manager = JobManager.new

manager.start_jobs


# elsewhere

manager.statuses? # returns [Job1.status?, Job2.status?]

This is the sort of idiom I'd use in my code. It's important to be aware that the status variables are subject to race conditions if they are not properly guarded against concurrent modification and access.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top