nokogiri not working in cron jobs

I have a ruby script that manipulates an RSS feed and saves it to a new file for display. The script uses nokogiri for handling the XML. Since the RSS feed updates regularly (obviously), I’ve been running it as a Scheduled Task on my workstation in Windows. But I wanted to move it to an Ubuntu server so it runs whether my workstation is powered on or not.

I put the job into my crontab:

00 08,12,17 * * * /usr/bin/ruby /home/username/bin/pcresfeed/pcresfeed.rb 2>> /home/username/pcres/log.txt

(The 2>> part sends errors to that logfile.) However, I kept getting an error that “cannot load such file -- nokogiri (LoadError)” in my log. This had me going around in circles for a while–executing the same command in bash worked fine; trying require 'nokogiri' in irb worked fine; RVM had nokogiri installed for every installed version of ruby; I tried various RVM wrappers. Nothing worked. I tried installing chruby at someone’s recommendation in #ruby on freenode. At this point things were getting pretty confusing, so I completely removed RVM and chruby, and restarted with just a plain apt-get ruby installation. Still nothing.

It turns out that my googling had been too narrow. I couldn’t find anything about the cron + nokogiri issue, but that’s because I should’ve been looking for cron + gems. (For some reason I was thinking that I had successfully cron’d other ruby scripts with gems on the same machine, but in retrospect they were probably all built-ins.) Stack Overflow to the rescue, as usual:

00 08,12,17 * * * /bin/bash -c '/usr/bin/ruby /home/username/bin/pcresfeed/pcresfeed.rb 2>> /home/username/pcres/log.txt'

So instead of calling the ruby executable, I’m calling bash and passing it my script as an argument. It turns out that it’s a problem of the cron’s environment being different from mine. I had thought that RVM’s or chruby’s cron integrations would get around this problem, but they don’t seem to apply to gems. Whew!

Leave a Reply

Your email address will not be published. Required fields are marked *