Question

I have a rake task in my Rails application,and when I execute the order in my rails app path /home/hxh/Share/ruby/sport/:

rake get_sportdata

This will work fine.

Now,I want to use crontab to make this rake to be a timed task .so,I add a task:

* * * * * cd /home/hxh/Share/ruby/sport && /usr/local/bin/rake get_sportdata >/dev/null 2>&1

But this doesn't work.I get the log in cron.log file:

Job `cron.daily' terminated

I want to know where the error is.

Was it helpful?

Solution

Does the "cd /home/hxh/Share/ruby/sport && /usr/local/bin/rake get_sportdata >/dev/null 2>&1" can work in your terminal?

But use crontab in Rails normally is not a good idea. It will load Rails environment every time and slow down your performance.

I think whenever or rufus-scheduler are all good. For example, use rufus-scheduler is very easy. In config\initializers\schedule_task.rb

require 'rubygems'
require 'rufus/scheduler'


scheduler = Rufus::Scheduler.start_new(:thread_name => "Check Resources Health")
scheduler.every '1d', :first_at => Time.now do |job|
  puts "###########RM Schedule Job - Check Resources Health: #{job.job_id}##########"
  begin
    HealthChecker.perform
  rescue Exception => e
    puts e.message
    puts e.backtrace
    raise "Error in RM Scheduler - Check Resources Health " + e.message
  end
end

And implement "perform" or some other class method in your controller, now the controller is "HealthChecker". Very easy and no extra effort. Hope it help.

OTHER TIPS

So that you can test better, and get a handle on whether it works I suggest:

  1. Write a shell script in [app root]/script which sets up the right environment variables to point to Ruby (if necessary) and has the call to rake. E.g., something like script/get-sportdata.sh.
  2. Test the script as root. E.g., first do sudo -s.
  3. Call this script from cron. E.g., * cd [...] && script/get-sportdata.sh. If necessary, test that line as root too.

That's been my recipe for success, running rake tasks from cron on Ubuntu. This is because the cron environment is a bit different than the usual shell setup. And so limiting your actual cron jobs to simple commands to run a particular script are a good way to divide the configuration into smaller parts which can be individually tested.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top