Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Execute ruby script from cron

My script uses mysql, tiny_tds, fileutils, and net/ftp. Running on ruby 1.9.3. It works perfectly fine when I run it from inside the folder.

However, when I add it to cron tab, tiny_tds constantly fails. I dont know if any of the other gems fail as I can't get passed this error:

require': no such file to load -- tiny_tds (LoadError)

I tried executing it from the same shell that crontab would use, and I get that error.

The entire script is just 1 file.

I'm new to ruby so my knowledge is limited in setting up the environment the right way.

In the head of the file I have

    #!/usr/bin/ruby
    require "mysql"
    require "fileutils";
    require "tiny_tds"  
    require "net/ftp"

In short, I get a list of Jobs from mysql, compare that against MsSQL, FTP files over and update mysql again when jobs are done.

And I need to run this from cron.

After researching for a bit, I tried to set set the gems as global, however, I think that may not have worked.

Thanks in advance for any help!

like image 938
Mike Avatar asked Mar 05 '13 23:03

Mike


2 Answers

This is because the environment variables you have on the command line are not set when crond executes you code. The usual suspects are PATH, LD_LIBRARY_PATH, and aliases that are set when you login.

You can see what crond does: using crontab -e

* * * * *  set > /tmp/setvals

create the above entry. let it run for a while. Go back into crontab -e and remove that new entry.

Compare what is in /tmp/setvals with what your shell gives you when you issue the set command on the command line. You can then take steps to modify things for your cron job's environment.

like image 199
jim mcnamara Avatar answered Sep 19 '22 14:09

jim mcnamara


There are multiple ways for RVM to cooperate with cron, if you use script then the simplest is just to use RVM - which means do not use system ruby #!/usr/bin/ruby - just put in the first line #!/path/to/rvm/wrappers/ruby-1.9.3-p392/ruby

you can use aliases to prevent hardcoding one ruby path in a script:

rvm alias create my_app 1.9.3

and then in script header (first line):

#!/path/to/rvm/wrappers/my_app/ruby
like image 43
mpapis Avatar answered Sep 17 '22 14:09

mpapis