0

I am importing gmail contacts, some users had huge number of contacts its taking long time to save in database. How to use in delay job to run in background asynchronously. I am using delay_job gem

Here is code I wrote

token = Google::Authorization.exchange_singular_use_for_session_token(params[:token])
unless token == false
  @contacts = Google::Contact.all(token)      
  @contacts.each do |contact|
    next if contact.email.nil?
    c = {
      :user_id => current_user.id,
      :source => 'gmail',
      :name => contact.name,
      :email => contact.email
    }
    c = Contact.find_or_initialize_by_email(c[:email])
    c.update_attributes(c)
  end
end
prasannaboga
  • 1,004
  • 1
  • 14
  • 36

1 Answers1

1

Add these gems in the Gemfile

gem 'ghazel-daemons'
gem 'delayed_job'

then run

bundle install

rails g delayed_job:active_record

rake db:migrate

Then use the delay method provided by delayed job to run the process in background

c = Contact.find_or_initialize_by_email(c[:email])
c.delay.update_attributes(c)

Start the delayed job process from the project root directory using the command,

rake jobs:work

For automating start/stop/restart after deployment, refer the documentation https://github.com/collectiveidea/delayed_job/wiki/Rails-3-and-Capistrano

For more options, on how to use delayed job methods, you can check this page https://github.com/collectiveidea/delayed_job

Amit Thawait
  • 4,862
  • 2
  • 31
  • 25