后台任务完成后如何通知用户?

时间:2016-11-08 12:52:33

标签: ruby-on-rails background-process sidekiq

我使用带有ActiveJobsidekiq的rails作为后端。当用户进入页面sidekiq创建长期后台任务时,如何在任务完成时注意到用户(通过在网页上呈现部分)?

Rails和sidekiq作为不同的进程工作。这个事实让我很困惑,我不明白如何使用后台工作处理完成状态。

2 个答案:

答案 0 :(得分:4)

ActiveJob提供after_perform回调,根据文档的工作方式如下:

class VideoProcessJob < ActiveJob::Base
  queue_as :default

  after_perform do |job|
    UserMailer.notify_video_processed(job.arguments.first)
  end

  def perform(video_id)
    Video.find(video_id).process
  end
end

因此,您无需担心直接与Sidekiq或任何其他排队后端集成,请与ActiveJob对话:)

答案 1 :(得分:1)

我在这种情况下的做法是:

  1. 添加sidekiq-status,以便按ID跟踪后台作业。
  2. 在创建后台作业的客户端调用中,返回新创建的作业ID。

    class MyController < ApplicationController
    
      def create
        # sidekiq-status lets us retrieve a unique job ID when
        # creating a job
        job_id = Workers::MyJob.perform_async(...)
    
        # tell the client where to find the progress of this job
        return :json => {
          :next => "/my/progress?job_id={job_id}"
        }
      end
    
    end
    
  3. 使用该作业ID轮询服务器上的“进度”端点。此端点获取作业的作业进度信息并将其返回给客户端。

    class MyController < ApplicationController
    
      def progress
        # fetch job status from sidekiq-status
        status = Sidekiq::Status::get_all(params[:job_id])
    
        # in practice, status can be nil if the info has expired from
        # Redis; I'm ignoring that for the purpose of this example
    
        if status["complete"]
          # job is complete; notify the client in some way
          # perhaps by sending it a rendered partial
          payload = {
            :html => render_to_string({
              :partial => "my/job_finished",
              :layout => nil
            })
          }
        else
          # tell client to check back again later
          payload = {:next => "/my/progress?job_id={params[:job_id]}"}
        end
    
        render :json => payload
      end
    
    end
    
  4. 如果客户端看到作业已完成,则可以显示消息或采取下一步所需的步骤。

    var getProgress = function(progress_url, poll_interval) {
      $.get(progress_url).done(function(progress) {
        if(progress.html) {
          // job is complete; show HTML returned by server
          $('#my-container').html(progress.html);
        } else {
          // job is not yet complete, try again later at the URL
          // provided by the server
          setTimeout(function() {
            getProgress(progress.next, poll_interval);
          }, poll_interval);
        }
      });
    };
    $("#my-button").on('click', function(e) {
      $.post("/my").done(function(data) {
        getProgress(data.next, 5000);
      });
      e.preventDefault();
    });
    
  5. 警告:该代码是说明性的,并且缺少您应该处理的事项,例如错误处理,防止重复提交等等。