If you try to use ruby in a cron script, there are certain errors or ‘gotchas’ that you should look out for. Hopefully this short ruby cron guide will save you a few minutes of debugging. The main problems for a ruby script in a cron file are improperly set permissions, improper environment, no new-line at end of cronfile, or an error in ruby script itself. Say i have a file in
/home/myuser/myfolder/myrubyscript.rb
First, make sure that this file has the proper permissions, i.e. read and execute permissions for the user that is running the cron. If you aren’t sure, just use 755 permissions, i.e.:
sudo chmod 755 /home/myuser/myfolder/myrubyscript.rb
Now that this script can be executed by cron, now you should set the environment properly, namely, that the environment when cron runs is different from your environment! Things such as the GEM_HOME path may not be set properly. To see your paths, make another cron job like this:
* * * * env > /home/myuser/cronenv.txt
This will create a file called cronenv.txt that lets you see what your environment is like when the cron job runs. You may need to set your PATH and your GEMHOME variables inside your crontab, so your cronfile should look something like this:
GEM_HOME=/usr/lib/ruby1.9.1/gems/1.9.1
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
* * * * * /usr/bin/ruby /home/myuser/myfolder/myrubyscript.rb
Another gotcha is that
the last line of your cronfile should be a line return
Check the /var/log/syslog to see if the cron job is running, and in parenthesis it should say what user it is running as. Make sure this user has the proper permissions as stated earlier (i.e. 755 on the file).
If you have done everything above and things still aren’t working, it probably means that there is an error inside of your file. A trick is to simply surround your topmost code in a begin / rescue block, and open a file a write any exceptions to a file, something like this:
f = File.open("/home/myuser/myerrors.txt","w")
f.puts "at the top of my file"
begin
.... my regular code....
rescue Exception=>e
f.puts "#{ e.message } #{ e.backtrace.join("\n")} "
end
