Skip to content

Commit ad1fa07

Browse files
committed
Merge pull request #198 from just3ws/master
Split up the actual sending of the emails to speed things up
2 parents 02ed896 + 1860d93 commit ad1fa07

File tree

2 files changed

+33
-13
lines changed

2 files changed

+33
-13
lines changed
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
class ProtipMailerPopularProtipsSendWorker
2+
include Sidekiq::Worker
3+
sidekiq_options queue: :low
4+
5+
def perform(user_id, protip_ids, from, to)
6+
fail "Only #{protip_ids.count} protips but expected 10" unless protip_ids.count == 10
7+
8+
begin
9+
if REDIS.sismember(ProtipMailer::CAMPAIGN_ID, user_id.to_s)
10+
Rails.logger.warn("Already sent email to #{user_id} please check Redis SET #{ProtipMailer::CAMPAIGN_ID}.")
11+
else
12+
Rails.logger.warn("Sending email to #{user_id}.")
13+
# In development the arguments are the correct type but in production
14+
# they have to be recast from string back to date types :D
15+
from = Time.zone.parse(from.to_s)
16+
to = Time.zone.parse(to.to_s)
17+
user = User.find(user_id.to_i)
18+
protips = Protip.where('id in (?)', protip_ids.map(&:to_i) )
19+
fail "Only #{protips.count} protips but expected 10" unless protips.count == 10
20+
21+
ProtipMailer.popular_protips(user, protips, from, to).deliver
22+
end
23+
rescue => ex
24+
Rails.logger.error("[ProtipMailer.popular_protips] Unable to send email due to '#{ex}' >>\n#{ex.backtrace.join("\n ")}")
25+
Rails.logger.ap([from, to, user_id, protip_ids], :error)
26+
end
27+
end
28+
end

app/workers/protip_mailer_popular_protips_worker.rb

Lines changed: 5 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -9,20 +9,12 @@ def perform(from, to)
99
from = Time.zone.parse(from.to_s)
1010
to = Time.zone.parse(to.to_s)
1111

12-
protips = ProtipMailer::Queries.popular_protips(from, to)
12+
protip_ids = ProtipMailer::Queries.popular_protips(from, to).map(&:id)
1313

14-
User.find_each(batch_size: 100) do |user|
15-
begin
16-
if REDIS.sismember(ProtipMailer::CAMPAIGN_ID, user.id.to_s)
17-
Rails.logger.warn("Already sent email to #{user.id} please check Redis SET #{ProtipMailer::CAMPAIGN_ID}.")
18-
else
19-
Rails.logger.warn("Sending email to #{user.id}.")
20-
ProtipMailer.popular_protips(user, protips, from, to).deliver
21-
end
22-
rescue => ex
23-
Rails.logger.error("[ProtipMailer.popular_protips] Unable to send email due to '#{ex}' >>\n#{ex.backtrace.join("\n ")}")
24-
Rails.logger.ap([from, to, user, protips], :error)
25-
end
14+
fail "Only #{protip_ids.count} protips but expected 10" unless protip_ids.count == 10
15+
16+
User.order('updated_at desc').find_each(batch_size: 100) do |user|
17+
ProtipMailerPopularProtipsSendWorker.perform_async(user.id, protip_ids, from, to)
2618
end
2719
end
2820
end

0 commit comments

Comments
 (0)