Reputation: 52580
I need some code executed once per day. Can be more than once a day and missing a day isn't the end of the world. That code will make sure users get some bonus points based on certain criteria. I'll keep track if they've already received the bonus points so it doesn't double up..
Some simple cron job calling a particular controller once in a while is perfect:
curl http://localhost/tasks/pulse
Of course a real crontab entry works great. Or is there an internal mechanism for this kind of thing in Rails? I'm using the latest stable Rails (currently 3.2.9).
The only wrinkle is this needs to work in Heroku too.
I just noticed Heroku's Scheduler. Looks great for Heroku. I can just run those tasks in my dev/test environment manually. Is this the best way to handle pulses/cron jobs in Rails? With rake tasks? Easy to incorporate running rake tasks in tests?
Upvotes: 0
Views: 478
Reputation: 63
Here's a quick example of how you can set it up, and how i'm currently using it on a prod environment
Add the sidekiq and sidekiq-cron gems to your Gemfile:
gem 'sidekiq'
gem 'sidekiq-cron'
Create a worker class for your tasks:
class RakeTaskWorker
include Sidekiq::Worker
def perform(task)
output = `bundle exec rails #{task} 2>&1`
status = $?.exitstatus
if status.zero?
Sidekiq.logger.info("Rake task '#{task}' executed successfully.")
else
Sidekiq.logger.error("Rake task '#{task}' failed with status #{status}: #{output}")
end
end
end
Define your cron job in config/schedule.yml
:
daily_bonus_worker:
cron: "0 0 * * *"
class: "RakeTaskWorker"
args:
- "generate:daily_bonus"
https://github.com/sidekiq-cron/sidekiq-cron
Upvotes: 0
Reputation: 1980
You could check out this gem called whenever its a Ruby gem that provides a clear syntax for writing and deploying cron jobs. It's well maintained, not used it on Heroku myself but worth a look.
You can do loads of stuff like
every 3.hours do
runner "MyModel.some_process"
rake "my:rake:task"
command "/usr/bin/my_great_command"
end
Upvotes: 0