1
require gmail
gmail = Gmail.connect("testemail@gmail.com", "password")
SidekiqWorker.perform_async(gmail, item.user_id)
gmail.logout()

I want to pass a object to sidekiq,It is a gmail client object,And I don't want to create that object in perform method ,so I am passing and its going in string format , I am taking the help of open struct to pass it, But its going in string format.

#OpenStruct gmail=#Gmail::Client0xbe18230 (abcd@gmail.com) connected>>
Identity1
  • 1,139
  • 16
  • 33
AJinkya
  • 21
  • 8
  • can any one suggest me some solution that how could I pass a connection to sidekiq ? – AJinkya Jan 27 '16 at 06:33
  • I would be surprised if an open connection from a web server to an external service which will be stored serialized in Redis would still work when it is de-serialized on the worker machine. I would at least expect that the connection is not working anymore or was closed, because it was interrupted, non existing in memory for some time and perhaps even moved to a different server. Why do you try to avoid creating the connection in the worker? – spickermann Jan 27 '16 at 07:28

1 Answers1

3

There are a couple of issues. I do not think the code above will work as you intend. The SidekiqWork is run asynchronously with the rest of the code. It looks like your code might be subject to a race condition. You cannot control if the worker code runs before or after the gmail.logout() call.

In addition, it's generally not considered a best practice to pass an object as an argument to a Sidekiq job. See the Sidekiq Best Practices. Instead, I might consider making the gmail connection from within the Sidekiq job.

As an alternative, you might consider using a class method in a lib class that stores an instance of the gmail client. You can memoize this connection like the following:

 class GmailClient
   def self.connection
     @client ||= Gmail.connect("testemail@gmail.com", "password")
   end
 end
  • As a third alternative, Sidekiq job might call back the method, closing the connection after the job is done. _Sidenote_: please, mention in the answer that the parameter passed as expected, not as a `String`, it’s only displayed as a string. – Aleksei Matiushkin Jan 27 '16 at 06:54