Search code examples
ruby-on-railsdelayed-job

How to send mails to 5 user per minute using Delayed Job


I am using rails 5.

I want to send emails to 100 users from my rails application.

I have added delayed_job gem to send emails asynchronously.

Following is the code:

controller:

UserMailer.delay.send_mail(email, subject, body)

Mailer:

def send_mail(email, subject, body)
  mail(to: email, subject: subject, body: body, content_type: "text/html")
end

Q. I need to know, how to send mails to 5 user per minute?

Q. If I used delayed_job to send mails to 100 users, there are 100 jobs under delayed_job table. Can I send mail in batches?


Solution

  • Assuming you want to send the same subject and body to every recipient, I would use find_in_batches and the run_at parameter.

    # UserMailer
    def send_email_batch(emails, subject, body)
      emails.each do |email|
        send_email(email, subject, body)
      end
    end
    
    # Controller
    now = Time.current
    User.find_in_batches(batch_size: 5).with_index do |users, batch|
      UserMailer.delay(run_at: now + batch * 60).send_email_batch(users.map(&:email), subject, body)
    end