ruby-on-rails - 作业完成后返回响应 - 延迟作业
问题描述
早些时候,我有我的控制器类,它正在创建服务实例并调用服务方法“同步”,如下所示。在“同步”方法完成后,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)?
解决方案
第 1 步。一旦您的延迟作业完成,它必须将您的同步方法的输出保存到数据库中。
步骤 2.在“UI”端,编写一个定期向服务器发送GET请求的方法。
第 3 步。您的控制器方法检查数据库并返回'Nil'
或返回延迟作业输出的 JSON 对象。
推荐阅读
- ruby-on-rails - 如何使用滚动版本升级 Rails 会话格式/加密
- three.js - Three.js - 用弧线生成形状
- sql - 如果另一列 = 1,则从离散概率分布中选择一个值?
- sapui5 - SAP Cloud Platform中Web Ide Full Stack中的测试部分如何使用?
- scala - 在 Generic 类型必须支持 add 或 + 函数的情况下使函数泛型
- rstudio - rworldmap-map-没有出现在 knit (html) 中
- angular - 在Angular 6中滚动结束时禁用按钮
- laravel - Laravel:中间件可以接受路由输入吗?
- swift - 我可以返回 switch 语句的 case 值吗?斯威夫特 4
- javascript - javascript中的模板文字