preloader
軟體工程

Crontab execute ruby job without failure

Below execution environment is at Ubuntu 14 LTS.

rvm cron setup

 

#sm start rvm example
PATH="/usr/local/rvm/gems/ruby-2.3.0/bin:/usr/local/rvm/gems/ruby-2.3.0@global/bin:/usr/local/rvm/rubies/ruby-2.3.0/bin:/usr/local/rvm/gems/ruby-2.3.0/bin:/usr/local/rvm/gems/ruby-2.3.0@global/bin:/usr/local/rvm/rubies/ruby-2.3.0/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/usr/local/rvm/bin"

GEM_HOME='/usr/local/rvm/gems/ruby-2.3.0'

GEM_PATH='/usr/local/rvm/gems/ruby-2.3.0:/usr/local/rvm/gems/ruby-2.3.0@global'

MY_RUBY_HOME='/usr/local/rvm/rubies/ruby-2.3.0'

IRBRC='/usr/local/rvm/rubies/ruby-2.3.0/.irbrc'

RUBY_VERSION='ruby-2.3.0'

#sm end rvm example

 

change from shell to bash shell

SHELL=/bin/bash

 

# you definie your own crontab job

0 0 * * * . $HOME/.profile; cd /directory/you/want/toexecute; ruby /path/to/yourfile.rb parameter1 parameter2 ...etc > /dev/null

0 1 * * * . $HOME/.profile; cd /directory/you/want/toexecute; ruby /path/to/yourfile.rb `date -d "yesterday" "+%F"` `date -d "today" "+%F"` > /dev/null

 

In above jobs of crontab, . $HOME/.profile statement is used to load values in user’s bash environment.

 

Redirect standard out to garbage:

> /dev/null

Redirect standard out and standard error to garbage together:

> /dev/null 2>&1

 

 

Reference:

http://stackoverflow.com/questions/20672583/requiring-a-ruby-gem-in-ruby-script-breaks-cron-job-execution

http://unix.stackexchange.com/questions/27289/how-can-i-run-a-cron-command-with-existing-environmental-variables

http://stackoverflow.com/questions/11059067/what-is-the-nix-command-to-view-a-users-default-login-shell

http://unix.stackexchange.com/questions/29578/how-can-i-execute-date-inside-of-a-cron-tab-job