Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Polling Worker Contoller in Rails
class MyController < ApplicationController
def new
end
def create
@job_id = MyWorker.perform_async(my_params)
render :status => :accepted, :json => { jobId: @job_id }
end
def fetch
job_id = params[:job_id]
if Sidekiq::Status::complete? job_id
render :status => 200, :text => Sidekiq::Status::get(job_id, :output)
elsif Sidekiq::Status::failed? job_id
render :status => 500, :text => 'Failed'
else
render :status => 202, :text => ''
end
end
protected
def my_params
params.require(:something).permit(:this)
end
end
class MyWorker
include Sidekiq::Worker
include Sidekiq::Status::Worker
def perform(params)
#do long work
#...
#...
av = ActionView::Base.new(Rails.root.join('app', 'views'))
av.assign({:outpout => @output})
store :output, av.render(:template => "my_controller/long_view.html")
end
end
<%= form_tag my_controller_create_path, method: :get, id: 'worker-form' do |f| %>
<%= fields_for "something[]" do |ff| %>
<%= text_field_tag :this %>
<% end %>
<%= submit_tag %>
<% end %>
<div id='result'>
</div>
<%= javascript_tag do %>
var sendJobForm = function(event) {
event.preventDefault();
var $form = $(this),
$submit = $form.find('input[type=submit]'),
$result = $('#result');
function output(msg) { $result.html(msg) }
function jobFinished(jobResult) {
$submit.val('Create Job').removeAttr('disabled');
$result.html(jobResult);
}
function pollJob(jobId, successCallback) {
function poll() {
var pollEvery = 3000; // milliseconds
$.ajax({
type: "GET",
url: "/my_controller/fetch/" + jobId, // coupled to your app's routes
dataType: 'text',
statusCode: {
200: function(data) { successCallback(data); },
202: function(data) { setTimeout(poll, pollEvery); },
500: function(data) { output('Error!'); }
}
});
};
poll();
}
$submit.attr('disabled', true);
output('Creating...');
$.ajax({
type: "POST",
url: $form.attr('action'),
data: $form.serialize(),
dataType: 'json',
success: function(data) {
output('Job queued, waiting...');
pollJob(data.jobId, jobFinished);
}
});
};
$('form').submit(sendJobForm);
<% end %>
get "my_controller/new"
get "my_controller/fetch/:job_id", controller: :my_controller, action: :fetch
post "my_controller/create"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.