问题
I only want to perform the background job when the user is logged in. When the user is logged in, I start a worker:
Warden::Manager.after_authentication do |user,auth,opts|
ImapWorker.perform_async(user.id)
end
All my ImapWorker does is use ruby's Net::Imap
API to wait for new emails to come in from a remote email server. It uses Imap's idle functionality to wait for new events.
class ImapWorker
include Sidekiq::Worker
def perform(user_id)
user = User.find(user_id)
imap = Net::IMAP.new('imap.gmail.com',993,true)
imap.login(user.email, user.password)
imap.select('INBOX')
imap.add_response_handler do |resp|
if resp.kind_of?(Net::IMAP::UntaggedResponse) and resp.name == "EXISTS"
check_email
end
end
imap.idle
end
end
Now when my user logs out, I want to end the worker. I know in devise
, I can hook into the log out functionality as such:
Warden::Manager.before_logout do |user,auth,opts|
...
end
But how exactly do I stop the sidekiq worker?
回答1:
require 'sidekiq/api'; Sidekiq::ProcessSet.new.each(&:stop!)
来源:https://stackoverflow.com/questions/39459985/stop-sidekiq-worker-when-user-logs-out