What is the best way to schedule a sending-email task with Ruby on Rails?

北城余情 提交于 2019-11-28 23:13:42

问题


I would like to schedule a daily task : every day at 7 AM, I want an email to be sent (without human intervention).

I'm working on the RoR framework and I'm wondering what is the best way to do that?

I've heard about BackgrounDRB, OpenWFEru scheduler or things based on Cron, but I'm a newbie and don't understand which one is made for my need.


回答1:


Another option is to create a rake task that is run by a cron job. To do this, create a file some_file.rake and put it in your lib/tasks folder. Your file might look like this:

Rails 2.x:

task :send_daily_mail, :needs => :environment do
    Model.send_daily_mail
end

Rails 3.x:

task :send_daily_mail => :environment do
    Model.send_daily_mail
end

Then use cron to execute it as often as you like:

cd /path/to/app && /usr/bin/rake send_daily_mail

Note you might need to put RAILS_ENV=production in your crontab if your app is in development mode by default.




回答2:


I was impressed by (and plan to try) the rufus-scheduler gem discussed in this blog post

He describes something like this:

scheduler = Rufus::Scheduler.start_new  

scheduler.every("1m") do  
   DailyDigest.send_digest!  
end 

..which seems pretty simple. I wonder how easy it would be to add HTML-based configuration?




回答3:


BackgroundRB is what I use and it works perfect. I have several emails being sent, generated by BackgroundRB. I also have other tasks as well. Because it enables both scheduled tasks and asynchronous tasks (tasks that take longer than the normal client/server response cycle).

I use it and I am very happy with it.




回答4:


Add a class method to one of your models that will handle this for you. Now try to execute that method using the runner script

./script/runner "MyModel.send_daily_mail" RAILS_ENV=production

Ensure everything works ok. If it does, then we need to make the command work universally by setting up the path to the project properly.

cd /path/to/my/rails/project && ./script/runner "MyModel.send_daily_mail" RAILS_ENV=production

Now change to any random directiry and run that command. If it runs properly, run crontab -e and insert the command in there setup to run daily at 7AM. There are a ton of explanation about the cron format on there if you google for them and should be pretty simple to figure out.




回答5:


Go with a rake task and cron job, as the accepted answer already says. However, note that, updating the cron file itself is a manual task. That may be fine if you are not changing it during development. Otherwise, here how you can let Capistrano do it for you: http://push.cx/2008/deploying-crontab-with-your-rails-app



来源:https://stackoverflow.com/questions/553648/what-is-the-best-way-to-schedule-a-sending-email-task-with-ruby-on-rails

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!