简体   繁体   中英

How can I get the output of delayed_job in rails

I have a "Status" page. On which I am displaying the status of my local machines such as current upload/download speed, is recording going or not.

For getting above information I am ssh into that machine. Here is my sample code for it

Net::SSH.start('localhost','ubuntu', :password => 'ubuntu') do |session|
    upload_speed = session.exec!("speedtest | grep Upload:").chomp.strip
    return upload_speed
end

But it is taking time (about 3-4 minutes) for fetching those status. And it returns me "Connection time out error". So I am trying to add this process in the background. For this I am using delayed_job gem

Here is my code for it My controller method

def unit_additional_status
    @machine = MachineInfo.find(params[:unit_id])    
    stat = Delayed::Job.enqueue(LongerTask.new(@machine), 3, :run_at => 1.seconds.from_now)
end

Here is my longer_task.rb file

    require 'rubygems'
    require 'net/ssh'

    class LongerTask < Struct.new(:machine)
      def perform
             port = @machine.port
             @status = Hash.new
             Net::SSH.start('localhost','ubuntu', :password => 'ubuntu', :port => port) do |session|
              upload_speed = session.exec!("speedtest | grep Upload:").chomp.strip
              status["upload_speed"].push(upload_speed) 
            end
            @status
      end
end

After execution I have to pass this @status to my controller action so that I can pass it to my status.html.erb view.

So I have a question how can I pass it to my controller method or how can get the output of execution of delayed job.

Also, if any one have better solution then let me know.

I am using rails 3.2.14 and ruby 1.8.7

You need to create some kind of additional status model, eg Job (status:string, message:string) . Then you pass an instance of this model to your delayed job task when it is scheduled. When the task starts executing, you set the status to 'running'. When it finishes you update the message field with the desired result information and set status to 'finished'. This has several benefits like you have a good overview of your job queue and it can be extended to reflect execution time, errors etc.

To display the machine status in your example, you simply select the latest Job with status='finished' and show its timestamp and message.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM