Indicate to an ajax process that the delayed job has completed

久未见 提交于 2019-11-30 06:50:22

问题


I have a Rails 3 app that uses delayed_job to fetch some data (with a class method) when the user hits the page. How can I indicate to the ajax process that the class method has run (so that I can stop polling)?

EDIT:

To clarify, I want to know when the delayed_job has run, not when the ajax process has succeeded. Then I want to pass the delayed_job completed status to the running ajax process.


回答1:


Typically, the best way to do this is to store, in your database, an indication of the job's progress. For instance:

class User
  def perform_calculation
    begin
      self.update_attributes :calculation_status => 'started'
      do_something_complex
      self.update_attributes :calculation_status => 'success' 
    rescue Exception => e
      self.update_attributes :calculation_status => 'error'
    end
  end
end

So that when you enqueue the job:

User.update_attributes :calculation_status => 'enqueued'
User.send_later :perform_calculation

You can query, in your controller, the status of the job:

def check_status
  @user = User.find(params[:id])
  render :json => @user.calculation_status
end

You polling ajax process can then simply call check_status to see how the job is progressing, if it has succeeded or if it has failed.




回答2:


With this gem you can have progress tracking directly on the Delayed::Job object itself: https://github.com/GBH/delayed_job_progress

Completed jobs are no longer automatically removed, so you can poll against a job until it comes back with completed state.




回答3:


If you are using any JavaScript framework like prototypejs, then in the optional options hash, you usually provide a onComplete and/or onSuccess callback. API Reference



来源:https://stackoverflow.com/questions/5042300/indicate-to-an-ajax-process-that-the-delayed-job-has-completed

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!