Running background DelayedJob task on Heroku, poll for updates and refresh in browser using Ajax

1. Fire a refresh_all request or per-item refresh requests from browser html javascript:

  $.ajax({ url: '/statuses/refresh_all',
  $('.status_table .refresh a').each(function(link) { $.ajax({ url: '/statuses/' + this.getAttribute('status_id') + '/refresh',
  => Status.fetch_all or Status.fetch(id)
     => heroku.post_ps_scale('worker', '1') if required
     => Delayed::Job.enqueue self       # schedule a background task
      => DJ schedules tasklet perform()
        => It does the background processing and updates timestamp in model "self.updated_at ="
      [ DJ after() triggers dj_killer_thread which waits for DJ to complete all jobs (Delayed::Job.count) and then scales down heroku worker dyno. ]

2. Keep on polling until a new response (generated after "last_modified") becomes available:

$(link).addClass('refreshing') # Change CSS to show progress animation (indicate polling)
$.ajax({url: '/statuses/' + status_id, headers: { 'If-Modified-Since': last_modified } # last_modified is $(link).attr('last_modified')
    => uses stale?() to check model @status.updated_at against last_modified received in client request and either returns:
  (200 Done) with results updated by the background process => Use innerHTML to update status (results) in-place.
  (304 Not Modified)       => sleep & go back to polling.

Note: In Application config.after_initialize, flush any leftover jobs by destroying Delayed::Job.all.

No comments:

Post a Comment