tags:

views:

230

answers:

4

Hi, I have a rake file, which can be executed successfully at command line. When I set a cronjob to run this rake file, the line "require 'json'" fails. My guess is that cronjob has a different env variable. It doesn't work when I tried to put "puts ENV" in the ruby script. So I'm wondering what I should do to check the different env variables and how to solve the problem. Thanks.

A: 

do you have

require 'rubygems'

in your script? E.g. irb loads rubygems by default, while normal execution requires explicit import.

inquiringmind
Yes I do have require 'rubygems'. If I run at commandline, rake data.rake, no problem. Error only happens at cronjob.
swingfuture
A: 

First: require "json" is probably failing because rubygems isn't loaded. You can probably fix that by either placing require 'rubygems' at the top, or by adding RUBYOPT=rubygems to the front of the cron job command line or to cron's environment (you can usually set environment variables in the crontab).

To answer your ENV debugging issue: is it possible that puts ENV isn't working because stdout is redirected somewhere you don't know about during the cron job (it certainly can't go to your terminal)? You could try the following instead:

File.open('/tmp/debug_env', 'w') do |f|
  f.puts ENV.to_hash.inspect
end

And then take a look in /tmp/debug_env to see what's there. Environment variables to especially look out for are $USER, $GEM_HOME, $GEM_PATH, $RUBYOPT.

nicholas a. evans
First I do have rubygems loaded, second, I tried your advice adding RUBYOPT=rubygems to the front of cronjob, same error. I'll try the ENV debugging.
swingfuture
+1  A: 

It might be how you're invoking it in cron. Here's what works for me:

cd /full/path/to/rails_root && /full/path/to/rake RAILS_ENV=production my:task
Sarah Mei
A: 

Another manner of doing it: write a wrapper script to run from cron: first line - load your .profile (or .bash_profile etc) second line - run your rake script

BZ