3/7/2018 - 2:49 PM


Using cron

What is cron?

  • Cron jobs, cron tasks or crontab
  • software written to help with the scheduling of reoccurring tasks
    • In your rails app, you may need to schedule reoccuring actions like checking for expired accounts or clearing out expired sessions from your database

Start Using Cron

  • cd in to your repo and in the terminal, execute: crontab -e
    • this will open up your default text editor, to select a text editor: EDITOR=nano crontab -e
  • Once inside the editor, you will need to specify when the task will run using the following format:
# +---------------- minute (0 - 59)
# |  +------------- hour (0 - 23)
# |  |  +---------- day of month (1 - 31)
# |  |  |  +------- month (1 - 12)
# |  |  |  |  +---- day of week (0 - 6) (Sunday=0)
# |  |  |  |  |
  *  *  *  *  *  command to be executed
  • You can use * to specify every unit of the part, so in the above you will schedule the task every minute of every hour on every day of every month every day of the week.
  • Use commas to sepearte values ... Monday, Wednesday ...
  • Follow the time span with a valid bash command, ex: bundle exec rails db:migrate
  • Cron is useful for running system and server tasks!
  • Also useful for running rails application code on a schedule, through a rake task!
    • to run a rake task you wil have to cd into your application root and then call rake
      • 0 0 * * * cd /my/app/root && /path/to/bundle exec rake some_task
      • run which bundle from within your app's root to find the path to bundle
  • Alternative to running rails commands is using rails runner ruby_code
    • 0 * * * * cd /my/app/root && /path/to/bundle exec rails runner -e production "Model.long_running_method"
    • -e production sets the environment to production
    • "Model.long_running_method" represents a class methodcalled from within your rails app
    • rails runner loads the app in memory first then evaluates the code in the environment specified. When the task completes, the runner exits!

Whenever Gem

  • used to better maintain and store your cron jobs!
  • Add gem "whenever", require: false to gemfile and then run bundle install
  • Within your app's root, run: bundle exec wheneverize
    • this will add to your config folder: config/schedule.rb
    • commands
    • Commands are now set, but you will need to apply them to your crontab, in the terminal:
      • cd in app root
      • bundle exec whenever: schedule.rb is converted to cron syntax
      • bundle exec whenever -i: update crontab
      • bundle exec whenever -w: overwrite the whole crontab
      • bundle exec whenever -h: see help
  • For more intense schedules consider using Sidekiq or if deployed on Heroku, Heroku Schduler