Reputation: 7012
I have a method that checks to see if a user has submitted a timesheet for the previous month and if they haven't, sends out an email reminder. This method needs to run everyday. There is no action made by any user to actually trigger this method, it simply runs at a set time everyday.
Any idea on the best way to implement this in Rails 3?
Upvotes: 3
Views: 6348
Reputation: 11385
I'm developing on Mac OS X, with our production machine on CentOS, but this should apply to Ubuntu as well.
I have a rake task defined in report.rake
namespace :report do
desc "Email stats"
task :email_global_stats, [] => :environment do |t, args|
StatsMailer.global_stats_email.deliver
end
end
And the bulk of the logic of checking for new stats then emailing it are defined in StatsMailer
. Then on the production machine, I have this in my crontab (accessed through crontab -e
):
30 7 * * * RAILS_ENV=production /usr/local/bin/rake -f /home/user/code/stats/current/Rakefile report:email_global_stats
It's set to 7:30 AM, just so that I don't have everything running at midnight. And then I want to test locally, I just run:
rake report:email_global_stats
from my development directory. You also have to make sure postfix
is running by typing this on Mac OS X:
sudo postfix start
Upvotes: 0
Reputation: 6862
Take a look at Resque Scheduler. You can set cron to 0 0 * * *
this will run your script everyday once.Here is railscasts on Resque.
Upvotes: 0
Reputation: 2293
Create a rake task to run the method + deliver emails and have a look at the whenever gem which can automate cron generation.
https://github.com/javan/whenever
Then you can create a whenever config file at "config/schedule.rb" with the following;
every 1.day, :at => '12:00 pm' do
rake "timesheet:check"
end
Upvotes: 3
Reputation: 3152
Do you necessarily need to run this as part of your rails app? Can it be factored out to be a service of its own?
If you can move this functionality out of your rails app and run on its own, you could simply write a ruby script and execute it at a scheduled time via a cron job.
It could get unnecessarily messy when it comes to within your rails app, because you'll need something to constantly poll the time and see if it's time to make a call to that method. A cron job is always the easier way to go for tasks like yours.
I'd be glad to point you to resources which will help you set up a cron job if you could tell me what operating system you're using.
Upvotes: 0