通过数据库中的处理状态轮询 Sidekiq 作业以完成

Polling Sidekiq Job for Completion via Processing State in Database

我正在尝试向我的用户显示一条简单的消息,同时正在创建他们的自定义 PDF 并将其通过 Paperclip 附加到模型。完成后显示预览。

我能找到的最简单的解决方案是 Mike Perham 在 this question 中的回复。 "Use the database to store the state of each photo and have Sidekiq update the state."

毫无疑问,您会注意到我仍在学习 Javascript、JQuery、Rails 以及如何编写好的 SO 问题。尽管如此,到目前为止,这就是我所拥有的科学怪人。

请告诉我我的工作方向是否正确?

# generate_insert.rb
class GenerateInsert 
  include Sidekiq::Worker
  def perform(customization_id)
    customization = Customization.find(customization_id)
    customization.update_attribute(:processing, true)
    # code to perform, generate PDF via Prawn and attach via Paperclip
    customization.update_attribute(:processing, false)
    customization.save!
  end
end

# customizations/show.html.erb
<div id='message'>First Message</div>

# messages.js
var i = 1;
var sampleMessages = [ "First Message", "Second Message", "Third Message" ];
    setInterval(function() {
        var newText = sampleMessages[i++ % sampleMessages.length];
        $("#message").fadeOut(500, function () {
            $(this).text(newText).fadeIn(500);
        });
    }, 1 * 3000);
});

# show.js.erb
$("#message").replaceWith("<%= j render 'customization' %>");

# poller.js
CustomizationPoller =
poll: ->
    setTimeout @request, 5000

request: ->,
    $.get($('???').data('url'))

jQuery ->
if $('#???').length > 0 // customization processing?
    CustomizationPoller.poll()

使用您拥有的工具,您似乎走在了正确的轨道上。在您的用户需要更强大的解决方案之前保持简单是恕我直言的好主意。

但是,如果您希望有更多这样的交互(即用户做某事并等待更新),您可以考虑使用网络套接字,甚至使用像 https://rethinkdb.com 这样的工具。当然,这取决于您计划进行多少次此类互动。