Search code examples
ruby-on-railsdeviseresquerails-activejob

Rails 4 - Active Job: Run Job Only When User Is Signed In


I'm currently using Active Job/Resque to pull from an external api. It works perfectly but I want it to periodically pull from the api (and update Records) while the user is signed in.

Devise provides the current_user method which I cannot seem to use and I can't seem to check the session to break the loop. If I put the logic in the controller then it impacts page loads, etc. which defeats the purpose.

Basically, this is what I want to do:

class PullApiJob < ActiveJob::Base
  queue_as :default

  def perform(current_user, info)
    while current_user
      #Logic to pull info from api and save into Info record
      sleep(200) 
    end
  end
end 

Solution

  • How about check session time every request and store in db. add session_timeout_at

    for every request,

    if current_user && DateTime.now > current_user.session_timeout_at
      current_user.update(session_timeout_at: DateTime.now + session_duration)
      # session_duration => session expire duration, ex) 30.minutes
    end
    

    Your job

    class PullApiJob < ActiveJob::Base
      queue_as :default
    
      def perform(current_user, info)
        while current_user.session_timeout_at > DateTime.now do
          # Your Logic
          sleep(200)
          current_user.reload # <- Must reload for check updated session_timeout_at
        end
      end
    end