Search code examples
ruby-on-railscronherokujobs

What's the syntax to run a cron job on heroku every hour?


I just acquired the paid version of Heroku's cron, in order to run some tasks every hour. What I would like to know is the syntax I should use to actually get it to run every hour. So far I have this, Could you please tell me if it's correct:

desc "Tasks called by the Heroku cron add-on"
task :cron => :environment do
  if Time.now.hour % 1 == 0 # run every sixty minutes?

    puts "Updating view counts...."
    Video.update_view_counts  
    puts "Finished....."

    puts "Updating video scores...."
    VideoPost.update_score_caches
    puts "Finished....."

    puts "Erasing videos....."
    Video.erase_videos!
    puts "Finished....."

  end

  if Time.now.hour == 0 # run at midnight

  end
end

I need to know if this line with the 1 in it is the way to go...

if Time.now.hour % 1 == 0

Thanks in advance for your help,

Best Regards.


Solution

  • If you want to run every hour, don't bother checking. Heroku will run it hourly.

    Since %1 will always return 0, better to just have:

    desc "Tasks called by the Heroku cron add-on"
    task :cron => :environment do
      puts "Updating view counts...."
      Video.update_view_counts  
      puts "Finished....."
      #...
    
      if Time.now.hour == 1 #1am
        #...
      end
    
    end
    

    Also, if you want to be able to run Video.update_view_counts when you need to, you could instead (after creating the rake task):

    Rake::Task["video:update_view_counts"].invoke
    

    That way you can run it inside of cron, and manually if needed