Requiring a Ruby Gem in Ruby Script Breaks Cron Job Execution

Requiring a Ruby Gem in Ruby Script breaks Cron Job Execution

You need to setup your crontab with rvm e.g:

rvm cron setup

With that rvm sets your environment variables in your crontab file

then you have a crontab file having this at the top:

PATH="/usr/local/rvm/gems/ruby-1.9.3-p194/bin:/usr/local/rvm/gems/ruby-1.9.3-p194@global/bin:/usr/local/rvm/rubies/ruby-1.9.3-p194/bin:/usr/local/rvm/bin:/usr/local/rvm/gems/ruby-1.9.3-p194/bin:/usr/local/rvm/gems/ruby-1.9.3-p194@global/bin:/usr/local/rvm/rubies/ruby-1.9.3-p194/bin:/usr/local/rvm/bin:/usr/lib64/qt-3.3/bin:/usr/local/bin:/bin:/usr/bin:/usr/local/sbin:/usr/sbin:/sbin:/usr/local/rvm/gems/ruby-1.9.3-p194@global/"
rvm_env_string='ruby-1.9.3-p194'
rvm_path='/usr/local/rvm'
rvm_ruby_string='ruby-1.9.3-p194'
RUBY_VERSION='ruby-1.9.3-p194'
GEM_HOME='/usr/local/rvm/gems/ruby-1.9.3-p194'
GEM_PATH='/usr/local/rvm/gems/ruby-1.9.3-p194:/usr/local/rvm/gems/ruby-1.9.3-p194@global'
MY_RUBY_HOME='/usr/local/rvm/rubies/ruby-1.9.3-p194'
IRBRC='/usr/local/rvm/rubies/ruby-1.9.3-p194/.irbrc'

Then you can stick your crontask beneath it

Using cron and ruby

Ok. After a couple of hours I finally solved this problem. And the solution is very easy. I don't know, why it's working only that way.
So, the solution:

1.Create bash script with this content:

#!/usr/bin/env bash

/Users/username/.rvm/gems/ruby-2.2.0/wrappers/ruby /path/to/your/ruby_script.rb

2. Configure cron file:

SHELL = /bin/bash
* * * * * /path/to/created/at/first/step/bash_script.sh

That's all!
It's working for me!

how to create a cron job to run a ruby script?

If your ruby is in non standard paths then personally I like to wrap my ruby calls in a shell script, thereby ensuring that all the paths etc. my ruby program needs are set correctly, and schedule the script in crontab. Do something like

2 * * * * /home/mark/project/ruby_wrapper_sh >> /home/mark/cronOutput.txt 2>&1

and your /home/mark/project/ruby_wrapper_sh should read something like

#!/bin/bash

. ~mark/.bash_profile
`ruby /home/mark/project/script.rb`

Ruby: CLI script failing when requiring gems installed through git

So the issue was I was running the script in question using ./bin/path/script

This will not work if the script includes github referenced gems, you need to prefix this with bundle exec which is not immediately obvious, given that when you use non-github referenced gems, it works fine without it.

Now running bundle exec ./bin/path/script will work for both, it's probably just better using that wherever possible.



Related Topics



Leave a reply



Submit