“...I've been working since 2008 with Ruby / Ruby on Rails, love a bit of Elixir / Phoenix and learning Rust. I also poke through other people's code and make PRs for OpenSource Ruby projects that sometimes make it. Currently working for InPay...”

Rob Lacey (contact@robl.me)
Senior Software Engineer, Brighton, UK

Rake tasks via Crontab with RVM

What seemed like a simple task has amounted to plenty of messing about. But here we go, the following didn’t work at all, it filled /var/mail/rails with junk and failure messages about missing a missing bundle command.

rails@fashion1-002:/var/www/app/current$ crontab -l
# m h  dom mon dow   command
0 5 * * * cd /var/www/app/current && bundle exec rake app:activity:rebuild
# 0 9 * * 1 cd /var/www/app/current && bundle exec rake app:jobs:digest
# */5 * * * * cd /var/www/app/current && bundle exec rails runner "SiteMailer.simple_message('contact@mydomain.me', 'Test', 'Test Cron Message').deliver"

You have to use Environment Variables in this case to specify RAILS_ENV although it is already defined in my .bashrc, also if you’re using RVM in order to use the correct version of Ruby you must use RVM’s own wrapper scripts. Lastly to stop the output from cron ending up in a dead mailbox or spamming you direct the output of the command to /dev/null

rails@fashion1-002:/var/www/app/current$ crontab -l
# m h  dom mon dow   command
0 5 * * * cd /var/www/app/current && RAILS_ENV=production /home/rails/.rvm/wrappers/ruby-2.1.2@app/bundle exec rake app:activity:rebuild > /dev/null
# 0 9 * * 1 cd /var/www/app/current && RAILS_ENV=production /home/rails/.rvm/wrappers/ruby-2.1.2@app/bundle exec rake app:jobs:digest > /dev/null
# */5 * * * * cd /var/www/app/current && RAILS_ENV=production /home/rails/.rvm/wrappers/ruby-2.1.2@app/bundle exec rails runner "SiteMailer.simple_message('contact@mydomain.me', 'Test', 'Test Cron Message').deliver" > /dev/null

Fixed.