Skip to content

Instantly share code, notes, and snippets.

@jch
Created August 16, 2013 22:01
Show Gist options
  • Save jch/6253842 to your computer and use it in GitHub Desktop.
Save jch/6253842 to your computer and use it in GitHub Desktop.
some pseudocode for polling long running jobs
# # PollingRequest
#
# A xhr request that repeatedly polls a [progress-aware endpoint](#progress-aware-endpoint).
#
# req = PollingRequest.new
# url: /states.csv
# interval: 2000 # polling interval in milliseconds
# progress: (n)->
# console.log "Progress: #{n} percent"
# success: (res)->
# window.location.assign(res.url)
# error: (msg)->
# alert("Error #{msg}")
#
# req.status # 'pending'
# req.run
# req.status # 'running'
# req.progress # 0
#
# # sometime later
# req.status # 'running'
# req.progress # 50
#
# # much later
# req.status # 'success'
# req.progress # 100
#
# ## Progress Aware Endpoint
#
# PollingRequests will have a header 'X-POLLING-REQUEST' set. It expects your
# endpoint to respond with a [202
# Accepted](http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.2.3)
# status code when there is more processing to be done. The JSON encoded
# response body must include a 'requestId' property for tracking this request.
# It's value must be unique across requests. The body can optionally include a
# `progress` property whose value is an integer 0..100 inclusive to indicate the
# percentage of processing completed.
#
# $ curl -i -H'X-POLLING-REQUEST:' http://localhost/endpoint
# HTTP/1.1 201 Accepted
# { requestId: 'custom-request-uuid', progress: 0 }
#
# # subsequent requests will include the requestId
# $ curl -i -H'X-POLLING-REQUEST: custom-request-uuid' http://localhost/endpoint
# HTTP/1.1 201 Accepted
# { requestId: 'custom-request-uuid', progress: 0 }
class PollingRequest
initialize: (options)->
@progress = 0
@status = 'pending'
@options = options
run: ->
return if @timer # already started
@timer = setInterval
$.ajax
url: options.url
beforeSend: (jqXHR, settings)->
@status = 'running'
statusCode:
# The request has succeeded.
200: (data, textStatus, jqXHR)->
@progress = 100
options.success(data)
stop
# The request has been accepted for processing, but the processing has
# not been completed. `data` must include a key `progress` with a
# integer value in the range 0..100.
202: (data, textStatus, jqXHR)->
, options.interval
stop: ->
clearInterval(@timer)
@timer = null
@jch
Copy link
Author

jch commented Aug 19, 2013

I'll probably combine this with resque-status or another plugin to report progress on background jobs.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment