Debugging Cron Jobs with Whenever Gem.

Is your program running at scheduled time?

First things first.

What is cron? Wiki says - "The software utility Cron is a time-based job scheduler in Unix-like computer operating systems. People who set up and maintain software environments use cron to schedule jobs (commands or shell scripts) to run periodically at fixed times, dates, or intervals"

What is crontab? It's a file, which contains information about cron job, maintains seperate files for individual users. It is not indended to edit directly.

If you are starting to wonder if this is new to you, checkout railscasts and whenever.

Cron Job and Whenever.

Consider an example.

set :output, "/application/current/log/cron_log.log"
every 5.minutes do
  runner "MyModel.method"
  command 'date'

Writing to custom log would help us debug easily, for more.
command 'date'
executes current time set on machine, and will be written to cron_log file

Integration with Capistrano.

For deployment purpose I have recently used Capistrano 3 also has integration for Whenever check this out

After this, on every deploy crontab file will be updated.

Crontab file

∴ crontab -l

# Begin Whenever generated tasks for: user_env

0,5,10,15,20,25,30,35,40,45,50,55 * * * * /bin/bash -l -c 'date >> /home/app_name/current/log/cron_log.log 2>&1'

0,5,10,15,20,25,30,35,40,45,50,55 * * * * /bin/bash -l -c 'cd /home/app_name/releases/RELEASE_ID && script/rails runner -e environment '\''MyModel.method'\'' >> /home/app_name/current/log/cron_log.log 2>&1'

# End Whenever generated tasks for: user_env

Note: The RELEASE_ID here will be pointing to latest release, which will be current folder(symblinked). If your crontab has repeatatively listed same task, which might be appending over on every deployment, then your server will be overloaded and will freeze and web server may not respond to any request.

Useful commands to debug.

There exists a log file path for most activities on linux:

/var/log/syslog (Ubuntu).
/var/log/cron (CentOs).
service cron status

where you can monitor if your cron is running or not.

  • whenever --help
  • crontab -l #to view and check for duplicates
  • crontab -e #to edit
  • crontab -r #to clear/delete user's crontab
  • sudo service cron restart #although not necessarily to be used

So that's it about Whenever and Cron, hope you find it useful.