Thursday, 27 November 2014

What do to when cron refuses do run your Ruby script (using RVM and Bundler)

The reason this was happening to me was that I was using RVM, as well Bundler on a production server. This was the first time I used RVM in production, and I hoped it would run super smooth... Alas!
The main Sinatra web application was running perfectly, but the background script simply would not run, and there was no output either. Adding some debug statements in crontab revealed that all other operations ran perfectly both before and after the Ruby script.
As it happens, cron does not run in the same environment as the shell, so RVM is completely gone. Without RVM there's no bundler or anything else Ruby. This became obvious when I started adding the "env" command redirected to a file in the crontab. The solution was to add the following lines in the crontab:
SHELL=/bin/bash
BASH_ENV=/home/[username]/.bashrc
Replace [username] with the correct username if you're running RVM in user mode, otherwise make it the path to the environment you want cron to run under.
Then you can execute the script as follows:
# m h  dom mon dow   command
* * * * * cd /home/[username]/path/to/script && source ~/.rvm/environments/ruby-2.1.5 && bundle exec "ruby ./my_script.rb >> log/my_script.log 2>&1"
Obviously, you need to use the path to the version of Ruby you use in the source statement above, and you need to keep this updated should you upgrade Ruby, unless you link to default (which is probably a good idea). To find out where the environments are, execute this:
ls -l $rvm_environments_path
RVM is a great tool, but this is a small inconvenience I did not count on. Now that I know, of course, it's no longer an inconvenience.

No comments:

Post a Comment