Search code examples
ruby-on-railscronrakescheduled-tasksdelayed-job

rake task via cron problem loading rubygems


I have managed to get a cron job to run a rake task by doing the following:

cd /home/myusername/approotlocation/ && /usr/bin/rake sendnewsletter RAILS_ENV=development

i have checked with which ruby and which rake to make sure the paths are correct (from bash)

the job looks like it wants to run as i get the following email from the cron daemon when it completes

Missing these required gems:
      chronic  
      whenever  
      searchlogic  
      adzap-ar_mailer  
      twitter  
      gdata  
      bitly  
      ruby-recaptcha

You're running:
  ruby 1.8.7.22 at /usr/bin/ruby
  rubygems 1.3.5 at /home/myusername/gems, /usr/lib/ruby/gems/1.8

Run `rake gems:install` to install the missing gems.
(in /home/myusername/approotlocation)

my custom rake file within lib/tasks is as follows:

task :sendnewsletter => :environment do
 require 'rubygems'
 require 'chronic'  
 require 'whenever'  
 require 'searchlogic'  
 require 'adzap-ar_mailer'  
 require 'twitter'  
 require 'gdata'  
 require 'bitly'  
 require 'ruby-recaptcha'
   @recipients = Subscription.all(:conditions => {:active => true})
    for user in @recipients
      Email.send_later(:deliver_send_newsletter,user)
    end
end

with or without the require items, it still gives me the same error ...

can anyone shed some light on this? or alternatively advise me on how to make a custom file within the script directory that will run this function (I already have a cron job working that will run and process all my delayed_jobs.

After Jonathans suggestion below I ran

env

as a cron job on its own and received the following output:

SHELL=/bin/sh
MAILTO=myemailaddress
USER=myusername
PATH=/usr/bin:/bin
PWD=/home/myusername
SHLVL=1
HOME=/home/myusername
LOGNAME= myusername
_=/usr/bin/env

does this mean it's not loading the ruby files properly? .... also took Jonathans advice and produced the following cron.sh file

#!/bin/sh
date
echo "Executing Matenia Rake Task"
PATH=/usr/bin:/bin
cd /home/myusername/approotlocation/
rake sendnewsletter

still getting the missing gems notice ... Cheers!


Solution

  • Easiest way to fix this (but kind of a shotgun approche) is from your shell type

    env | grep PATH

    Then take this output and add it your crontab for that user

    so it would look something like this

    PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin
    
    # m h dom mon dow user    command
    42 6 * * *        root    job1
    47 6 * * 7        root    job2
    52 6 1 * *        root    job3
    

    Just make sure your gems's are inside of that path