RoR: Using CRON and Actionmailer to send daily email updates to all users
What ex开发者_开发百科actly would be the best way to go about using a cron task to send daily e-mails of updates to all users on my network? The e-mail would be made up of different information from multiple models.
I want to do something like "1 new friend requests : name ..." from the request model and user model and "There are 3 upcoming events from your friends: event name hosted by name..." from the event and user model.
I realize this is a common task but I didn't see much information on it, so any general tips about doing something like this would be greatly appreciated!
Side note: I will be using the Heroku daily cron plug-in to accomplish this if that matters (although I don't think it should).
I usually just write a rake task and add it to CRON.
The rake task will look like this:
namespace :notifications do
desc "Sends notifications"
task :send => :environment do
MyModel.all_users_to_notify.each do |u|
MyMailer.notification(u).deliver
end
end
end
And your crontab should look like this:
RAILS_ENV=production
HOME=/path/to/your/rails/app
PATH=/path/to/ruby/binaries
30 17 * * * rake notifications:send
If anyone else is looking for this answer, I recommend using the whenever gem for cron tasks. This will keep you from having to write a rake task, as well as giving you a nicer cron syntax:
app/mailers/my_mailer.rb:
class MyMailer < ActionMailer::Base
def my_email
...
end
end
config/schedule.rb
job_type :runner, "cd :path && rvm 2.0.0 do bundle exec script/rails runner -e :environment ':task' :output"
every 1.days, at: "7:00 am", roles: [:app] do
runner "MyMailer.my_email.deliver"
end
精彩评论