marc78
marc78

Reputation: 35

Heroku Scheduler rake task aborts

I'm pretty new to Rails and for the first time, I want to use Heroku Scheduler to run periodical tasks in my rails application. As advised in the Tutorial, I created the following rake tasks in /lib/tasks/scheduler.rake

 desc "This task is called by the Heroku scheduler add-on"
task :auto_results => :environment do
    puts "Updating results..."
    @cups = Cup.all
@cups.each do |cup|
    cup.fix_current_results
end
    puts "done."
end

task :update_game_dates => :environment do
    puts "Updating game dates..."
    @cups = Cup.all
@cups.each do |cup|
    cup.update_game_dates
end
puts "done."
end

The task run fine in my local environment, but after pushin to Heroku and running the task, each abort with the following error:

rake aborted!
undefined method `name' for nil:NilClass

To me it seems that Heroku somehow can't access the database and so doesn't revieve an object on which it can perform methods.

Ideas anyone?

Upvotes: 1

Views: 829

Answers (1)

Thomas Klemm
Thomas Klemm

Reputation: 10856

You could do the following:

Use a class method in your Cup model. You can then call it using the rails runner Cup.my_class_methodcommand, and schedule this in the Heroku scheduler.

# app/models/cup.rb
class Cup < ActiveRecord::Base
  # Your existing code

  ##
  #  Class Methods
  #  that can be run by 'rails runner Cup.my_class_method'
  #  with the Heroku scheduler
  def self.auto_results
    find_each {|cup| cup.fix_current_results}
  end

  def self.update_game_dates
    find_each {|cup| cup.update_game_dates}
  end
end

Then schedule rails runner Cup.auto_resultsand rails runner Cup.update_game_dateswith the Heroku scheduler.

I've optimizied your code a litte in the process, ask away if you have any questions.

Upvotes: 1

Related Questions