首页 > 解决方案 > 作业完成后返回响应 - 延迟作业

问题描述

早些时候,我有我的控制器类,它正在创建服务实例并调用服务方法“同步”,如下所示。在“同步”方法完成后,rails 用于将 JSON 消息呈现回我的 node.js。

if @service.valid_connection?
      @service.synchronize
      render json: {
        status: :unprocessable_entity,
        errors: @service.message
      }, status: :ok
    else
      render json: {
        status: :unprocessable_entity,
        errors: @event.errors.full_messages
      }, status: :ok
    end

但是,由于我的“同步”方法执行时间有点长,我创建了一个延迟作业来占用我的“同步”任务。所以目前我的控制器看起来像这样

if @service.valid_connection?
      ::Events::WegSyncJob.perform_later(event_id, b_cancelled)
    else
      render json: {
        status: :unprocessable_entity,
        errors: @event.errors.full_messages
      }, status: :ok
    end

现在我不能将我的渲染 JSON 放在这里,因为它会在作业传递给 delay_job 后立即执行,我在 Job 类中使用 after_perform 方法:

after_perform do |job|
    //below code is wrong
    render json: {
      status: :ok,
      message: "Check notifications"
    }, status: :ok
  end

  def perform(event_id, b_cancelled)
    //call to synchronize
  end

但是,我不能从我的 Job 类中调用“渲染”,因为它只能从控制器中调用。完成此后台作业后,如何将 JSON 消息呈现回我的 node.js (UI)?

标签: ruby-on-railsresponsesidekiqdelayed-jobrails-activejob

解决方案


第 1 步。一旦您的延迟作业完成,它必须将您的同步方法的输出保存到数据库中。

步骤 2.在“UI”端,编写一个定期向服务器发送GET请求的方法。

第 3 步。您的控制器方法检查数据库并返回'Nil'或返回延迟作业输出的 JSON 对象。


推荐阅读